Last active
December 11, 2015 22:39
-
-
Save mattfitzgerald/4671042 to your computer and use it in GitHub Desktop.
Email fetcher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'net/imap' | |
class InboundEmailFetcher | |
MAILBOXES = {success: "INBOX.processed", failure: "INBOX.failed"} | |
def config | |
@config ||= YAML.load_file("#{Rails.root}/config/incoming_mailer_daemon.yml")[Rails.env].to_options | |
end | |
def fetch | |
create_mailboxes | |
imap.select('INBOX') | |
imap.uid_search(["ALL"]).each do |message_id| | |
email = imap.uid_fetch(uid_id, ['RFC822']).first.attr['RFC822'] | |
mark_as_read id | |
if IncomingMailer.receive(email) | |
copy_email id, MAILBOXES[:success] | |
else | |
copy_email id, MAILBOXES[:failure] | |
end | |
imap.uid_store(uid_id, "+FLAGS", [:Deleted]) | |
end | |
imap.expunge() # delete emails flagged :Deleted | |
disconnect_imap | |
end | |
def imap | |
@imap ||= connect_imap | |
end | |
def connect_imap | |
@imap = Net::IMAP.new(config[:server]) | |
@imap.login(config[:username], config[:password]) | |
@imap | |
end | |
def mark_as_read id | |
imap.uid_store(id, "+FLAGS", [:Seen]) | |
end | |
def copy_email id, mailbox | |
imap.uid_copy(id, mailbox) | |
end | |
def disconnect_imap | |
imap.logout() | |
imap.disconnect() | |
end | |
def create_mailboxes | |
MAILBOXES.values.each do |mailbox_name| | |
imap.create(mailbox_name) unless remote_mailbox_names.include? mailbox_name | |
end | |
end | |
def remote_mailbox_names | |
@mailbox_names ||= imap.list("","*").map(&:name) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment