Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
IMAP Mail Receive Ruby
#encoding: utf-8
class ContatoMailer < ActionMailer::Base
def receive(message)
p message
end
end
# default rails environment to development
ENV['RAILS_ENV'] ||= 'development'
require File.expand_path(File.dirname(__FILE__) + "/config/environment")
require 'net/imap'
require 'net/http'
config = YAML.load(File.read(File.join(RAILS_ROOT, 'config', 'mail_receiver.yml')))
config = config[RAILS_ENV].to_options
sleep_time = config.delete(:sleep_time)
# this script will continue running forever
loop do
begin
# make a connection to imap account
imap = Net::IMAP.new(config[:host], config[:port], true)
imap.login(config[:username], config[:password])
# select inbox as our mailbox to process
imap.select('Inbox')
# get all emails that are in inbox that have not been deleted
imap.uid_search(["NOT", "DELETED"]).each do |uid|
# fetches the straight up source of the email for tmail to parse
source = imap.uid_fetch(uid, ['RFC822']).first.attr['RFC822']
# Location#new_from_email accepts the source and creates new location
contact = ContatoMailer.receive(source)
# there isn't move in imap so we copy to new mailbox and then delete from inbox
#imap.uid_copy(uid, "[Gmail]/All Mail")
imap.uid_store(uid, "+FLAGS", [:Deleted])
end
# expunge removes the deleted emails
imap.expunge
imap.logout
imap.disconnect
# NoResponseError and ByResponseError happen often when imap'ing
rescue Net::IMAP::NoResponseError => e
puts "No Response Error: #{e}"
# send to log file, db, or email
rescue Net::IMAP::ByeResponseError => e
puts "Bye Response Error: #{e}"
# send to log file, db, or email
rescue => e
puts "Fatal Error: #{e}"
# send to log file, db, or email
end
sleep(sleep_time)
end
development:
host: "imap.gmail.com"
port: 993
username: "username@gmail.com"
password: "password"
sleep_time: 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment