Created
May 25, 2012 11:15
-
-
Save andrerpbts/2787384 to your computer and use it in GitHub Desktop.
IMAP Mail Receive Ruby
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
#encoding: utf-8 | |
class ContatoMailer < ActionMailer::Base | |
def receive(message) | |
p message | |
end | |
end |
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
# 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 |
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
development: | |
host: "imap.gmail.com" | |
port: 993 | |
username: "[email protected]" | |
password: "password" | |
sleep_time: 10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
won't work if your INBOX is HUGE.