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.


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


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...'
sg = SendGridAPIClient(SENDGRID_API_KEY)

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

html_content = f"""
<p>Hello {name},</p>
<p>Welcome to <a href="">{APP_NAME}</a></p>
<p>Desmond Lua</p>

message = Mail(
    from_email=Email('', "Desmond Lua"),
    subject=f"Welcome to {APP_NAME}",

    # request_body = message.get()
    # response =
    response = sg.send(message)"email.status_code={response.status_code}")
except HTTPError as 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.