Skip to content

Instantly share code, notes, and snippets.

@jotaki
Created January 26, 2013 10:46
Show Gist options
  • Save jotaki/4641646 to your computer and use it in GitHub Desktop.
Save jotaki/4641646 to your computer and use it in GitHub Desktop.
Find and download attachments in gmail's sent mail.
#! /usr/bin/env ruby
# tested with ruby-1.9.2p320
# no additional gems should be required as net/imap is
# part of the default "library"
require 'net/imap'
# imap server (gmail)
$server = 'imap.gmail.com'
# email address (login)
$account = 'account@gmail.com'
# password for account
$passwd = 'S0me_5ecuR3!pa$$WD%%'
# minimum size (this is a dumb check, but hopefully good enough.)
$min_attachment_size = 8192
# Should not need to edit below this.
####
imap = Net::IMAP.new($server, 993, true)
imap.login $account, $passwd
imap.examine '[Gmail]/Sent Mail'
imap.search(%w{ALL}).each do |msg_id|
size = imap.fetch(msg_id, 'RFC822.SIZE').first.attr['RFC822.SIZE']
next if size < $min_attachment_size
p "msg '#{msg_id}' appears to meet size criteria, downloading"
body = imap.fetch(msg_id, 'BODY').first.attr['BODY']
i = 1
until body.parts[i].nil?
name = body.parts[i].param['NAME']
i += 1
attachment = imap.fetch(msg_id, "BODY[#{i}]").first.attr["BODY[#{i}]"]
unless File.exists? name
File.new(name, 'w').write attachment.unpack('m').first
p "Wrote #{name}"
else
p "#{name} appears to exist already, skipping..."
end
end
end
imap.logout
imap.disconnect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment