Gmail: Send email API In ruby on rails

A few days ago, I had a requirement to send email on behalf of users. Of course, the  user has given permissions to do so 🙂 We were not using any particular gem in the project for calling Google API, instead we were using a Rest Client.

Initially I went trough the API Documentation and since the basic architecture is already there, it was just a matter of calling the API through the rest client and my job is done. However, as usual, it’s not as easy as it looks.

After reading the API Docs, I figured out that I need to pass the basic parameters (to, cc, bcc, subject, body) in raw text and as per the format of RFC 2822, in a  bese64url encoded string. But in the doc they didn’t mention that to, cc, etc should be separated by ‘,’ or ‘\n’. And I started complaining about the poor documentation to my colleagues, someone correctly pointed out it should be in RFCC 2822 format. What indeed is RFC 2822? When I did  read rfc 2822, I realized my mistake. The documentation was correct but who cares to read the doc carefully?

So according to RFC 2822 each field should be separated by ‘\n’ and body should be followed by header and separated by extra empty line. Following is code snippet I used to create raw string.

    def convert_to_base_64(to, cc, bcc, body, subject)
      message = "to: #{to}"
      message = message + "\n" + "subject: #{subject}" unless subject.blank?
      message = message + "\n" + "cc: #{cc}" unless cc.blank?
      message = message + "\n" + "bcc: #{bcc}" unless bcc.blank?
      message = message + "\n" + "content: multipart"
      message = message + "\n" + "Content-Type: text/html"
      message = message + "\n\n" + "#{body}"
      Base64.urlsafe_encode64(message)
    end

Note that I have added 2 ‘\n’ before body.

I wasted my day to figure this out might be this will save someone’s time.

Lesson Learnt: Always read documentation carefully.

2 thoughts on “Gmail: Send email API In ruby on rails

Leave a comment