Setup SendGrid Email With Python

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 loggingfrom sendgrid import SendGridAPIClientfrom sendgrid.helpers.mail import Mail, Emailfrom python_http_client.exceptions import HTTPErrorlog = 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><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="[email protected]",    from_email=Email('[email protected]', "Desmond Lua"),    subject=f"Welcome to {APP_NAME}",    html_content=html_content    )message.add_bcc("[email protected]")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.

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.