July 23, 2010
Posted by roadburn
How to: Receive email in rails with mail fetcher
Dan Weinand and Luke Francl have written a nice plugin which simplifies the task of retrieving emails. Kudos to them!
So basically what you need to do is install the plugin, create the Action Mailer receiver, and then use cron to schedule the script to run
Here are the steps:
First install the fetcher plugin from http://github.com/look/fetcher/ and SystemTimer gem it requires
$ script/plugin install git://github.com/look/fetcher.git $ sudo gem install SystemTimer
Create your ruby script eg. script/mail_fetcher
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/environment.rb' require 'system_timer' require 'yaml' require 'fetcher' begin puts "Start checking email" Lockfile.new('cron_mail_fetcher.lock', :retries => 0) do config = YAML.load_file("#{RAILS_ROOT}/config/mail.yml") config = config[RAILS_ENV].to_options fetcher = Fetcher.create({:receiver => EnquiryMailer}.merge(config)) fetcher.fetch end rescue Lockfile::MaxTriesLockError => e puts "Another fetcher is already running. Exiting." end
Create the config/mail.yml file
defaults: &defaults # Settings for gmail type: imap # pop OR imap server: imap.gmail.com # server hostname port: 993 # 993 for IMAPs ssl: true # Remove if not using SSL username: user@gmail.com # Username password: xxx # Password use_login: true # Required for GMAIL processed_folder: processed error_folder: error # settings for bluehost type: imap # pop OR imap server: boxXXX.bluehost.com # server hostname port: 993 # 993 for IMAPs ssl: true # Remove if not using SSL username: user@domain.com # Username password: xxx # Password use_login: true processed_folder: INBOX.processed error_folder: INBOX.error development: <<: *defaults # Override other values here test: <<: *defaults # Override other values here production: <<: *defaults # Override other values here
Create your Action Mailer
$ script/generate mailer EnquiryMailerAdd the receiver in app/models/enquiry_mailer.rb
class EnquiryMailer < ActionMailer::Base def receive(email) # do whatever you want with the email here # you can use: # email.subject, email.from, email.body end end
Run the script
$ script/runner script/mail_fetcher
Then follow Ryan Bate’s screencast on how to use Cron in Ruby
Resources

