Setup SendGrid Email With Python

May 28, 2019

Why Use SendGrid

Some comparisons/discussions

I haven’t try other options like Mailgun, Mailjet or Amazon SES, so I can’t do a comparison.

Nice things about SendGrid:

  • The Free plan seems to be 100 emails/day, but signing up via Google Cloud Marketplace seems to offer 12,000 emails/month on the free plan.
  • Plenty of client libraries, I mainly use sendgrid-python.
  • It does comes with a template editor, which support dynamic parameters, and you can choose to export the template.
  • Documentation is not top notch, but bearable.

Pre-requisite

Create a SendGrid account, or signup via Google Cloud Marketplace to enjoy 12,000 emails/day on the free plan.

Create an API Key.

Python Setup

Install sendgrid.

pip install sendgrid

Code

import logging
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, Email
from python_http_client.exceptions import HTTPError

log = logging.getLogger(__name__)

SENDGRID_API_KEY = 'SG.xx-mm...'

APP_NAME = "Lua Software Code"
name = "Desmond"

html_content = f"""
<p>Hello {name},</p>
<br>
<p>Welcome to <a href="https://code.luasoftware.com/">{APP_NAME}</a></p>
<br>
<p>From,</p>
<p>Desmond Lua</p>
"""

message = Mail(
    to_emails="to@email.com",
    from_email=Email('desmond.lua@luasoftware.com', "Desmond Lua"),
    subject=f"Welcome to {APP_NAME}",
    html_content=html_content
    )
message.add_bcc("bcc@email.com")

try:
    # https://github.com/sendgrid/sendgrid-python/blob/master/TROUBLESHOOTING.md#error
    # request_body = message.get()
    # response = sg.client.mail.send.post(request_body=request_body)
    response = sg.send(message)
    log.info(f"email.status_code={response.status_code}")
except HTTPError as e:
    log.error(e)

NOTE: I bump into python_http_client.exceptions.BadRequestsError: HTTP Error 400: Bad Request error because I accidentally put in an invalid email, but the error isn’t very helpful. Refer to this to extract a meaningful error messages.

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.