<img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=1870732089876948&amp;ev=PageView&amp;noscript=1">

A Robust Integration with SendGrid

Effective Email | CloudbakersSome of the most valuable components in our apps are the integration points between our applications' code, the client’s existing systems (e.g. CRM, accounting systems, etc), and third-party APIs like Twilio or Stripe. These integration points are typically simple to implement and rarely consist of more than a few lines of code, until you start to consider all of the exceptions that can occur when interacting with an outside API. A reliable integration requires code that is not only bug-free, but also robust enough to handle cases where external APIs fail to behave as expected.

Saving time with email boilerplates

SendGrid is a transactional email service that we leverage in a lot of our apps to deliver boilerplate emails for things like password resets, daily digests, and alerts. The Sendgrid API makes it easy to send emails from Python code and handle any arise that may occur when interacting with their API. The following code snippet shows the simplicity of making a request to the SendGrid API, as well as the complexity of correctly handling its response.

import sendgrid

def example_email():
    # Build a sendgrid Mail object
    msg = sendgrid.Mail()
    msg.to = "someone@example.com"
    msg.subject = "Hello World!"
    msg.html = "A robot sent you this message!"
    msg.from_email = "jordan@cloudbakers.com"
    msg.from_name = "Jordan Hawkins"
    sg = sendgrid.SendGridClient(SENDGRID_API_KEY)


        response = sg.send(msg)
    except sendgrid.exceptions.SendGridError as e:
        # Handle case where SendGrid fails to return a response altogether
        # by passing msg object to a queue that will retry the request later
        return retry_request(msg)

    # take different actions based on the status code returned from SendGrid API
    status_code = response[0]
    if status_code == 200:
        # 200 response - SendGrid was able to process the request.
        return True
    elif status_code == 400:
        # 400 response - the request was either incomplete or malformed in some way.
        # Notify dev team to fix the issue
        return notify_dev_team(response)
    elif ... : # handle other response codes

Damage control with push notifications

Handling the response is important to ensure that SendGrid processed your request and queued it up to be delivered, but what if the message still fails to make it to its destination? What if the intended recipient’s email server blocks or bounces the message? We can use SendGrid’s Event Webhook to deliver push notifications to our application and confirm a successful delivery.

The following screenshot shows an example webhook that you can configure in SendGrid by going to Settings > Mail Settings > Event Notification. When a message is dropped, deferred, bounced, or marked as spam, an HTTP POST request will be sent to a view in our app (shown below as example-app.appspot.com/sendgrid_events) with more information about the event.

Example Webhook

This kind of functionality is incredibly valuable when delivering messages that the user expects to be timely, such as an email confirmation or password reset. If the message fails to make it to the user for whatever reason, this webhook will notify your /sendgrid_events view, which can then forward the information along to your support staff with instructions to investigate the issue and notify the end user.

Third-party services like SendGrid will inevitably add another layer of complexity and uncertainty to any application, but using these two techniques will hopefully provide some peace of mind by assuring that your communications are being sent successfully - and raising the alarm when they fail!

New Call-to-action

Originally published on August 29, 2016

If you enjoyed this post, please consider sharing

Want more tech tips?
Subscribe to our IT Superhero Newsletter!