Recently a client told me that he does not like monitoring mails and its related statistics(sending, recieveing, mail open count, etc.) through http://www.sendgrid.com . Nothing wrong with SendGrid’s web interface, but it is for situation like this, the awesome folks at SendGrid have also released their api’s.

Before diving deep into their documentation, I decided to talk to people who have used sendgrid (not necessarily through api) and the common notion was that understanding sendgrid’s documentation is a very tedious job. I came to the conclusion that it is one of those things that you have to do it all by yourself, talking to people wont help much. So I got started with their docs without wasting any time. As I spent more and more time going through the docs, I realized it is not as intimidating as I was being told. So I decided that I would write down my understanding of their api and how you could use it with ruby applications.

So, there are lot of things you could do it with sendgrid api like creating and sending marketing emails, creating webhooks, setting inbound parse hooks, filter emails based on various categories. Here in this post, I would cover how to fetch list of marketing emails, create and send marketing emails to a list of recipients.

For any request we make, SendGrid requires us to send username and password along with other request parameters. It should also be noted that the response would be json when json requests are made and xml when xml requests are made.

So, lets assume sendgrid username and password are stored in environment variables. So we can access them as ENV[‘sendgrid_username’] and ENV[‘sendgrid_password’].

Now lets see how can I retrieve the list of existing marketing emails?  We would send a POST request. The url would be https://sendgrid.com/api/newsletter/list.json

I would recommend using Ruby’s rest-client gem. So to fetch a list of existing marketing emails, you would do

require 'rest_client'
url = "https://sendgrid.com/api/newsletter/list.json"
params = {"api_user" => ENV['sendgrid_username'], "api_key" => ENV['sendgrid_password']}

result = RestClient.post url, params

If you would notice that it is a post request that we have made. Any parameter that we need to pass, we would pass it through params in a key-value format. The response would look like this, if success it could be like this,

[
  {
    "name" : "marketing email 1",
    "newsletter_id" : 12345
  },

  {
    "name" : "marketing email 2",
    "newsletter_id" : 12344
  }
]

and if it fails for some reason, the response would be like this,

{
  "message" : "error"
}

Now that we have seen how to send a POST request, we move onto something which is a little more tricky. I will show you how to send an already existing marketing email to bunch of users. The tricky part is not in sending requests, but in following the whole process which is not documented anywhere. I could figure this out because before using their api, I tried the whole process through their web-ui and I realized pretty early that I have to do all this stuff (in same order) while doing it through api (or as I would like to say throu;gh Ruby code).These are the following steps you have to follow to send a marketing email to a bunch of users,

#STEP1  get list of all the marketing emails from sendgrid, choose email to send.
#STEP2  create an empty list to which recepients will be added.
#STEP3  add recipients email ids to this list.
#STEP4  attach this list to the marekting email to be sent.
#STEP5  send the mail.

I have already covered step 1 which is to get the list of marketing emails. Now to create an empty list, you would do

url = "https://sendgrid.com/api/newsletter/lists/add.json"
params = {"api_user" => ENV['sendgrid_username'], "api_key" => ENV['sendgrid_password'], "list" => list_name}

result = RestClient.post url, params

Here in the parameters we need to pass the name of the list. The response of this request could be either of “success” or “error” like these,

{
  "message" : "success"
}

and

{
  "message" :  "error"
}

Now that we have created an empty list, its time we see how to add users to this list. While adding recipients to the list, it is mandatory to add email and name of the recipient to the supplied data.  Lets look at the code we would do to complete this step.


url = "https://sendgrid.com/api/newsletter/lists/email/add.json"
users =  [
  {
    "name" :  "rishi",
    "email" :  "testmail@testsite.com"
  },
  {
    "name" :  "rocky",
    "email" :  "rocky@testsite.com"
  }
]

users.each do |user|

  params = {"api_user" => ENV['sendgrid_username'], "api_key" => ENV['sendgrid_password'], "name" => email_template, "list" => list_name, "data" => { "email" => user["email"],  "name" => user["name"] } }
  params['data'] = params['data'].to_json

  result = RestClient.post url, params
end

Here the success response is a little different. Lets see the different response it could give. In case of success, it would be like this

{
  "inserted" : 2
}

The number represents the number of users added to the list and in case of failure, its the same as rest of the failure messages.

For adding users to an empty list, it would generally take couple of minutes to reflect the changes. To be on the safe side, assume it would take 5 minutes to attach users to the list. So plan your next step not before 5 minutes.

As mentioned above, proceed ahead only after a delay of 5 minutes. So next step would be attaching this list to the marketing email.

  url = "https://sendgrid.com/api/newsletter/recipients/add.json"
  params = {"api_user" => ENV['sendgrid_username'], "api_key" => ENV['sendgrid_password'], "name" => email_template, "list" => list_name}

  result = RestClient.post url, params

The response here is a message, either success or error. After we have obtained success in this step, the penultimate step is to schedule the delivery of the mail.

  url = "https://sendgrid.com/api/newsletter/schedule/add.json"
  params = {"api_user" => ENV['sendgrid_username'], "api_key" => ENV['sendgrid_password'], "name" => email_template, "after" => 10 }

  result = RestClient.post url, params

In the parameters, we can also pass an option “after” to schedule the delivery of the mail after this much time from now. And also the response here is either “success” message or “error” message.You can do a lot more in sendgrid. You can read it here. So to sum it up, I hope this post helps you in understanding sendgrid a little better.

Advertisements

SendGrid’s API used with Ruby

One thought on “SendGrid’s API used with Ruby

  1. Hi Rishi, very good explanation on how to use the API. We are just trying to do the same but have encountered a lot of problems when trying to add big quantity of emails to a marketing list (around 20.000). I wanted to know if you encountered the same problems and how did you solve them.

    For example, Sendgrid’s API specify that you can send 1.000 users per request to add them to a list, but when we try to send the data by GET the URL is not valid because is too large, so we tried by POST but for our surprise you can’t send more than 1 user because the data POST parameter doesn’t allow an array.

    We are not using RestClient but i don’t think it makes a difference with the problems we have encountered…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s