Fetch Email Attachments with Ruby on Rails
This snippet is used in one of my projects to automatically import a csv into the database. It uses cron to check an email account via IMAP. When a unread email is found it will try to match it to subject lines in the database. If there is an entry it will attempt to import the attachment in the email. Once done it will email me the results.
I have deleted lines of code which relate to my specific needs to just give you the overview.
Uses Net::IMAP and TMail.
class MailImporter
def self.check_for_emails
completed ||= {}
imap = Net::IMAP.new(‘imap.gmail.com’,993,true)
imap.login(“[email protected]”, “mygmailpassword”)
imap.select(‘INBOX’) #which folder
imap.search([“NOT”,”SEEN”]).each do |message_id| #only get messages which are not read
if MailImporter.receive(imap.fetch(message_id, “RFC822”)[0].attr[“RFC822”])
imap.store(message_id, “+FLAGS”, [:Seen]) #mark read
end
imap.logout()
imap.disconnect()
completed.each do |data_email, leads|
DataEmailMailer.deliver_imported #email me
end
end
def self.receive(email)
mail = TMail::Mail.parse(email)
data_email = DataEmail.find_by_subject mail.subject #store subject lines in database, only import those which match, could link subject lines to another model if the import has any belongs_to or has_manys
if data_email
MailImporter.import_attachment(data_email, mail.attachments.first) unless mail.attachments.empty?
else
false
end
end
def self.import_attachment(data_email, attachment)
csv = attachment.read
FasterCSV.parse(csv) do |row|
#parse the row somehow and add it to your DB
end
true #return true if it all went well, could use a condition here and relate it to the import
end
end
Related Posts
In: Ruby on Rails · Tagged with: attachment, automation, cron, email, import, TMail