Thursday, July 2, 2009

Use tmail and IMAP to save attachments

#! /usr/bin/ruby

require 'net/imap'
# This is a convenience monkey patch
class Net::IMAP
def uid_move(uid, mailbox)
uid_copy(uid, mailbox)
uid_store(uid, "+FLAGS", [:Deleted])
end
end
require 'rubygems'
require 'tmail'

imap = Net::IMAP.new('mail.example.com')
imap.login("user", "password")
imap.select('Inbox')

imap.uid_search(["SUBJECT", "order mail"]).each do |uid|
# save_attachment
mail = TMail::Mail.parse( imap.uid_fetch(uid, 'RFC822').first.attr['RFC822'] )
if ! mail.attachments.blank?
File.open(mail.attachments.first.original_filename,"w+") { |local_file|
local_file << mail.attachments.first.gets(nil)
}
end

# archive mail to mailbox
imap.uid_move(uid, 'Inbox.archived')
end

imap.expunge
imap.logout
http://snippets.dzone.com/posts/show/7530

No comments: