Incoming emails with Ruby on Rails

Incoming emails with Ruby on Rails

You might have found yourself asking yourself:

“How does Direct Invoice transform what I’m responding to this email into a fine looking comment?”

The answer is simple.

As every good Ruby on Rails programmer, we have searched for a gem. This gem was everything we needed to perform what we were looking for. It’s name is Griddler.

“Griddler is a Rails engine that provides an endpoint for services that convert incoming emails to HTTP POST requests. It parses these POSTs and hands off a built email object to a class implemented by you.”

Okay, let’s read the documentation and begin!

Once having added the route,

post '/email_processor' => 'griddler/emails#create'

we configured Mandrill (which we use to send and receive emails) to send incoming mails to our application via this route.

But this route doesn’t make everything!

How does it know where to put the comment, on which invoice?

You might also have noticed the response-to parameter into the mails you receive from Direct Invoice. If not, here’s an example:

From: Direct Invoice <notifications@direct-invoice.com>
To: <invoice@dandycoding.com>
Reply-To: Direct Invoice <invoice-a4235265bd499441019df7e401c710e642@mail.direct-invoice.com>

Write ABOVE THIS LINE to post a comment or open the document online.

Hello,

A new comment has been written on the document 3 days Ruby on Rails coaching.

“Thank you, this was a great coaching session!”

Yay, there!

The invoice followed by the ugly hash; this is the point!

invoice tells the app’ that it’s an invoice (thanks!) while the hash is there to find the one the comment is for.

Thanks to Griddler, in our EmailProcessor class, we have a marvelous Griddler::Email object provided to us. With the method to, we get a collection of the different email recipients.

email.to.first[:token]

The first one is the one we need the token of!

After a pretty handy parsing, we retrieve the hash and find the invoice corresponding.

Now to get the comment from this whole mess of information that is the email, Griddler have thoughtbot about it!

The method body on the Griddler::Email object has already all we need! We just had to configure Griddler to know where to begin parsing.

config.reply_delimiter = "Write ABOVE THIS LINE to post a comment or open the document online."

Now, if you’ve responded well (I mean by that: if you’ve replied ABOVE the line), Griddler should have stored your reply into body and we just need to transform it into a comment.

And that’s all folks!

Join Thousands of Top Companies

Get started for free today. No credit card required. Cancel anytime.