Yesterday I got some really exciting news. One of my favorite dev shops, thoughtbot, released a gem that will help you receive email in your Ruby on Rails app called Griddler. The best part? It’s done using the SendGrid parse API! In this post, I’ll walk you through integrating it in a sample app in no time.
Let’s start with a really simple sample application that displays a list of posts. We only need one model, Post, and it has a body and email attributes. We could easily scaffold that out with the following command:
We also have a Posts controller with an index method and view that lists out all the posts:
The first thing we need to do is add Griddler to our dependencies. Add the following line to your Gemfile:
The next thing we need to do is create an EmailProcessor class that will handle all the incoming emails. In this example, I’m going to put it in my models folder because lib isn’t autoloaded by default, but it’s probably not best practice to put it in there. The class will have a process method that will get called with the new email object whenever we receive a mail. Whenever it gets called, we’re going to create a new post with the email’s body as it’s body and the from address as the email.
Now we have to do is set up a new parse endpoint on SendGrid. To do this, you’ll need to make sure your app is accessible from the web. You could deploy it somewhere like heroku or use the awesome localtunnel gem to expose your local development environment to the web.
You’ll also need a domain with it’s MX record pointing at mx.sendgrid.net. If you don’t know how to do this part, check with your domain’s hosting provider for details.
Head over to the Parse Webhook settings page and create a new record. Your hostname should be your url and the url should point to your app’s email processing endpoint. Griddler adds “/email_processor” as a route on your application. So, if your app is hosted at http://example.com, then the url would be “http://example.com/email_processor”.
That’s it! We’ve just integrated incoming email support into our sample application. Now every time you send an email to an email address at your domain, a new post gets created with the email’s body and the from email address.
Of course, just like many of ThoughtBot’s other awesome libraries, Griddler is open source. You can find the source code on Github, so be sure to check it out!