5 Best Practices for Using SendGrid With Google App Engine
SendGrid TeamNow that SendGrid joined the Google Cloud Platform Partner Program, it’s extremely simple to integrate email into your Google App Engine apps. In addition to helping get your email delivered, we offer statistics and advanced APIs to send, receive and analyze email. Below you’ll learn five key lessons for using SendGrid with Google App Engine.
1. Get Started
The first thing you need to know is that Google App Engine developers can send a lot of emails through SendGrid for free. Before you dive into any of the examples below, be sure to register your account to claim your free emails.
2. Use SendGrid Client Libraries
There are two main ways to send email through SendGrid. You can change your SMTP server settings or you can use the Web API. Both let you harness the same feature-set, but some of the advanced tools are easier with the Web API. The client libraries simplify the process even more by wrapping the HTTP calls in methods you can reference in popular programming languages.
There are special libraries built specifically for Google App Engine developers running Java or Python.
Python
Copy the SendGrid Python library into your project by placing the files in a SendGrid sub-directory. Then you’ll need a couple import statements and just a few lines of code:
from sendgrid import Sendgrid
from sendgrid import Message
# make a secure connection to SendGrid
s = sendgrid.Sendgrid(”, ”, secure=True)
# make a message object
message = sendgrid.Message(“from@mydomain.com”, “message subject”, “plaintext message body”, “HTML message body”)
# add a recipient
message.add_to(“someone@example.com”, “John Doe”)
# use the Web API to send your message
s.web.send(message)
Java
Copy SendGrid.java to the src directory of your app. You’ll import this class so that you can create a SendGrid instance and send mail with simple commands:
import packageName.Sendgrid
// set credentials
Sendgrid mail = new Sendgrid(“”,”");
// set email data
mail.setTo(“foo@bar.com”)
.setFrom(“me@bar.com”)
.setSubject(“Subject goes here”)
.setText(“Hello World!”)
.setHtml(“Hello World!”);
// send your message
mail.send();
3. Engage the Event API
Once you start sending email from your app, you’ll want to know more about how it’s performing. The statistics within SendGrid are one of its best features. The Event API lets you see all this data as one giant firehose. There are many different ways you could use the data. Some common uses are to integrate mail stats into internal dashboards or use it to respond immediately to unsubscribes and spam reports. Advanced users of the Event API raise the engagement of their emails by sending only to those who have clicked or opened within the last few months.
Technically, the Event API is a webhook. Whenever an event registers within SendGrid’s system, it fires off a bit of descriptive JSON to your app, which can react or store the data however you want.
The Nine Events
-
Processed — Message has been received and is ready to be delivered.
-
Dropped — Message will not be delivered, either by error or the address is suppressed.
-
Delivered — Message was accepted by receiving server (not necessarily inbox)
-
Deferred — Recipient’s email server temporarily rejected message.
-
Bounce — Receiving server could not or would not accept message.
-
Open — Recipient has opened the HTML message (with images enabled)
-
Click — Recipient clicked on a link within the message.
-
Spam Report — Recipient marked message as spam.
-
Unsubscribe — Recipient clicked on messages’ subscription management link.
Activate the Event API
The nine events provide a fairly complete a picture of your app’s email. To feed this data back into your app, you’ll need to configure the Event API in your account.
-
While logged into SendGrid enable the Events app
-
Edit the Event app settings
-
Choose the events you want to send a notification–why not all nine?
-
Enter the URL for the endpoint within your Google App Engine app where you want to receive events.
Save the changes and now any of the selected events will be send to your app as JSON.
Events as JSON
Every message may trigger a dozen or more events. Each is sent separately, unless you tell SendGrid to batch events. A single event is just a simple bit of JSON.
For example, here’s how an open event might look:
{"timestamp": "1234567890", "email": "adam@example.com", "event": "open"}
Some events send additional data, such as a status code or the URL clicked. You’ll find all the potential fields detailed in the Event API documentation.
If you batch event calls, you’ll receive multiple events at a time. Batched events currently post every second, or when the batch size reaches 1MB (one megabyte), whichever occurs first. Batched events look exactly like individual events, but are separated by a newline:
{"timestamp": "1234567890", "email": "adam@example.com", "event": "open"}
{"timestamp": "1234567890", "email": "eve@example.com", "event": "delivered"}
{"timestamp": "1234567890", "email": "able@example.com", "event": "processed"}
4. Set Categories and Unique Arguments
If the Event API lets you harness the firehose of email data from SendGrid, categories and unique arguments help you filter that firehose. As you send email, you can add categories and unique arguments through either SMTP headers or the Web API. Later, you can view statistics on subsets of email or dive into individual records.
First, it’s a good idea to understand the difference between the two:
- Categories help organize your email analytics by enabling you to tag emails by type. For example, you may want to track analytics separately on password reset messages. Or perhaps you want to perform cohort analysis or otherwise segment your users. You can have unlimited categories, creating an endless number of ways to analyze your email.
- Unique arguments are a used to attach data to individual emails. For example, you may want to include a registered user id in an email so events can quickly be tied back to an account. Where categories are used to group emails together, unique arguments keep them separated.
Both categories and unique arguments are added with x-smtpapi headers by including them as JSON values:
{
"category": "Example Category",
"unique_args": {
"user_id": 1235,
"first_name": "Pedro"
}
}
Multiple categories can be set by wrapping them in an array:
{
"category": [
"rocks",
"rivers",
"trees"
]
}
If you use the SendGrid client libraries, you don’t even need to worry about the JSON syntax for adding categories and unique arguments.
Python
message = sendgrid.Message("from@mydomain.com", "subject", "plain body", "<strong>Html here</strong>")
# set two categories for this message
message.add_category(["Category 1", "Category 2"])
# set 'Customer' to a value of 'Someone'
message.add_unique_argument("Customer", "Someone")
Java
Sendgrid mail = new Sendgrid("","");
// set two categories for this message
mail.addCategory("Category 1");
mail.addCategory("Category 2");
// set 'Customer' to a value of 'Someone'
mail.addUniqueArgument("Customer", "Someone");
5. Get Interactive with Inbound Parsing
SendGrid is really good at sending email, but there’s a lesser-known feature to receive email. The Inbound Parse API can be used for powerful, interactive applications. For example, automate support tickets from customer emails, or collect data via short emails employees dispatch from the road. NudgeMail’s reminder application is even built entirely on the Parse API.
Like the Event API, the Parse API is a webhook that sends data to your application when something new is available. In this case, the webhook is called whenever a new email arrives at the domain you’ve associated with incoming email. Due to intricacies in the way DNS works for email, you need to assign all incoming mail to the domain or sub-domain you use for the Parse API.
Set Up DNS
Making a change to your DNS means updating the MX record wherever you manage your DNS. Typically, this would be a domain registrar, hosting company or a DNS service.
Point the MX Record of the domain/hostname or sub-domain to mx.sendgrid.net. Remember, all incoming email will now flow through SendGrid, so don’t use a domain where you are currently receiving email.
DNS can take anywhere from a few minutes to several hours to propagate, so it’s important to set this up right away.
Point to Your Endpoint
While logged into your SendGrid account, navigate to the Parse API settings. To add a new endpoint where emails will be directed, you’ll need to include the following information:
- Hostname is the domain or sub-domain where emails that you want parsed will be sent.
- URL is the endpoint within your Google App Engine app where you want to receive emails as data.
- Spam Check is an optional filter to restrict potential spam from being passed along.
- Click the Add button and you should see your endpoint in the list of Hosts & URLs.
Read Emails as JSON
Once DNS has propagated and your endpoint is enabled, any email sent to the hostname you used will be sent to your endpoint. Developers love reading JSON and with the Parse API that’s exactly what an email becomes.
{
"from": "adam@example.com",
"to": "eve@example.com",
"subject": "Parse API example",
"html": "<p>Body of email in HTML (if set by sender)</p>",
"text": "Text body of email (if set by sender)"
}
There are more fields that come within the JSON, including attachments. That’s all explained in SendGrid’s Parse API documentation.
Now you’re set up receiving email with SendGrid, in addition to sending.
If you implement all five of these SendGrid Best Practices, you’ll be an email power user. Get started now with SendGrid on Google App Engine by claiming your free emails and downloading the libraries.