Tony Pitale

Recieve Gmail Email Messages in Rails

I want to announce the release of mail_room and tell you a little bit about it and how it fits in with your Rails app.

Suppose you have a Rails application, and you would like to receive email from your customers, your users, or someone else. Out of the box, the mail gem can get messages from a POP3 server and allows you to query for messages in a very nice way. Unfortunately, in order to receive new mail, you have to ask the server at regular intervals.

With mail_room, we can let gmail's IMAP do the work, using the IDLE command. As soon as a message arrives, mail_room will get it to your application.


At its simplest mail_room will forward your incoming gmail email to a URL you define.

It starts and runs as a process on its own. Given a configuration file like this, mail_room will open a connection for each gmail account and use the IMAP IDLE command to wait for new mail to come in. As soon as new mail arrives, mail_room will POST to the delivery_url you have configured.

Messages are sent to your application's delivery_url as RFC822 and can be received and parsed by the mail gem. From the mail object, you can see from, to, subject, body, and html for the message.

A delivery_token can be set to provide a simple mechanism to verify the sender. If an https delivery_url is provided, mail_room uses the excellent Faraday under the covers. By default, Faraday will attempt to use a verify_mode of OpenSSL::SSL::VERIFY_PEER.

Trying it out

If you'd like to try it out, but don't have an endpoint to receive the messages from mail_room, it can be configured to do more. Messages can be written to a log file, or better yet, they can be received and opened by Ryan Bates' (of Railscasts) fantastic gem, letter_opener.

Descriptions of the other configuration parameters for delivery methods can be found in this section of the README.

Start it up from your terminal using mail_room -c /path/to/config.yml.

When you're ready, you can simply use the mail gem to parse the body that mail_room sends using Mail.read_from_string(message). In this example 'message' is the POST body.

Next Steps

mail_room has greatly simplified the code I need to have in my Rails applications in order to have email pushed to me.

  • Try it out for yourself.
  • Watch the code for updates, new features, and an end-to-end example Rails integration.
  • Open an issue for any problems or questions you have.

Read More Recent Posts