Zak Ainsworth

Receiving Email in Rails

Receiving email in Rails is fairly easy using the ActionMailer class. The challenge is getting email to ActionMailer. Here's my solution.

Getting email into Rails can be done several different ways. I found that unless you have root privileges on your host, most of them won't work. The easiest option for me was to pull mail from a POP3 server using getmail.

Create a Rails project in ~/myproject. mkdir ~/myproject
cd ~/myproject
rails .

Create a model to handle all email related tasks. Let's call it EmailSystem. cd ~/myproject
./script/generate mailer EmailSystem

Open ~/myproject/app/models/email_system.rb and add something similar to this

Download getmail and extract it into ~/myproject. cd ~/myproject
wget http://pyropus.ca/software/getmail/old-versions/getmail-4.6.3.tar.gz
tar -zxvf getmail-4.6.3.tar.gz
mv getmail-4.6.3 getmail
Note: Version may be different.

Create the file ~/.getmail/getmailrc and make it look like this: [retriever]
#Credentials
type = SimplePOP3Retriever
server = pop3.example.com # <= Your pop3 server
username = [username] # <= Your username
password = [password] # <= Your password[destination]
# Send to Rails
type = MDA_external
path = /usr/bin/env
arguments = ("RAILS_ENV=production", "sh", "-c", "cd ~/myproject; /usr/local/bin/ruby script/runner 'EmailSystem.receive(STDIN.read)'")
[options]
# Delete email on server
delete = On
Note: Make sure you change the RAILS_ENV in ~/.getmail/getmailrc to whatever environment you are running in.

Now you can run getmail and it will collect all email from your pop3 account and send it to your EmailSystem model. ~/myproject/getmail/getmail Note: You might want to think about creating a cron entry to do this for you.

So, that's it. It seems to work pretty good for me. Let me know if you have any trouble.

Updated: June 16th, 2007