Tuesday, November 27, 2007

Cheap Tricks XII - Read SSL Email and Attachments

I need to connect to gmail to grab reports sent to me as attachments -- I'm also not using ActionMailer. What to do? Ruby/Gmail has two issues working against it: SSL required (POP3 SSL only available via trunk) and POP3 doesn't have built-in attachment-grabbing support. This is a quick-and-dirty hack to download the attachments as a file.

require 'net/pop'

BASE_DIR = "/tmp/attachements"

Net::POP3.enable_ssl(OpenSSL::SSL::VERIFY_NONE)
Net::POP3.start('pop.gmail.com', Net::POP3.default_pop3s_port, 'email@gmail.com', 'passwd') do |pop|
if pop.mails.empty?
puts 'No mail.'
else
pop.each_mail do |email|
msg = email.pop

msg.scan(/content-type: application\/octet-stream;\s*name=(.*?)\s*content-transfer-encoding: base64(.+?)(---)?/m) do |v|
filename = $1.to_s
data = $2.to_s.strip.unpack('m*')
File.open("#{BASE_DIR}/#{filename}", File::CREAT|File::TRUNC|File::WRONLY) do |f|
f.write(data)
end
end
end
end

0 comments: