top of page

How to Send Email Notifications in Python Using Twilio SendGrid

  • Chandan Rajpurohit
  • 15 hours ago
  • 3 min read

Whether you are building an alert system for your application, sending welcome emails to new users, or delivering daily reports, email automation is a core requirement for most modern applications.


While Twilio is famous for SMS and voice APIs, they power email through Twilio SendGrid one of the most robust email delivery services available.


Here is a complete guide to getting your Python application to send its first email using the SendGrid API.


Prerequisites


Before diving into the code, ensure you have:

  • Python 3.6+ installed on your machine.

  • A Twilio SendGrid account (the free tier allows up to 100 emails per day).

  • Basic familiarity with python and the command line or terminal.


Set Up SendGrid and Authenticate Your Domain


To prevent your emails from landing in the spam folder, SendGrid requires you to verify your identity.


  1. Log into your SendGrid dashboard.

  2. Navigate to Settings > Sender Authentication.

  3. Choose Single Sender Verification (best for quick testing) or Domain Authentication (recommended for production).

  4. Fill out the required details and verify your email address via the confirmation link sent to your inbox.


Note: You must use this verified email address as the "From" address in your Python script.


Generate an API Key


Your Python script needs permission to send emails on your behalf.


  1. In the SendGrid dashboard, go to Settings > API Keys.

  2. Click Create API Key.

  3. Give it a descriptive name (e.g., "Python App Emailer") and select Restricted Access -> Mail Send (Full Access).

  4. Copy the generated API key immediately. You will not be able to see it again once you close the window.


For security, never hardcode this key in your script. Instead, set it as an environment variable in your terminal:


On macOS/Linux:

export SENDGRID_API_KEY="your_api_key_here"

On Windows (Command Prompt):

set SENDGRID_API_KEY="your_api_key_here"

Install the SendGrid Python SDK


SendGrid provides an official Python library that abstracts away the complexity of raw HTTP requests. Install it using pip:

Bash

pip install sendgrid

Write the Email Script (Python)


Create a new file named send_email.py and add the following code. This script builds the email object and passes it to the SendGrid client.

import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

def send_notification():
    # 1. Construct the email message
    message = Mail(
        from_email='your_verified_email@example.com', # Must match Step 1
        to_emails='recipient@example.com',
        subject='System Alert: Task Completed Successfully',
        html_content='<strong>Success!</strong> Your background job has finished processing.'
    )

    try:
        # 2. Initialize the client using the environment variable
        sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
        
        # 3. Send the email and capture the response
        response = sg.send(message)
        
        # 4. Output the results
        print(f"Status Code: {response.status_code}")
        print(f"Headers: {response.headers}")
        print("Email dispatched successfully!")
        
    except Exception as e:
        print(f"Error: {e}")

if __name__ == '__main__':
    send_notification()
How the Code Works:

  • Mail(...): This class constructs your email payload. It handles the formatting required by the API.

  • os.environ.get(...): This safely retrieves your API key from the system environment, keeping your credentials out of version control.

  • sg.send(message): This executes the actual POST request to SendGrid's servers.


Execute and Verify


Run the script from your terminal:

python send_email.py

If everything is configured correctly, you will see a Status Code: 202 printed in your terminal.


This indicates that SendGrid has successfully accepted the message and queued it for delivery. Check the recipient inbox (and spam folder, just in case) to see your automated message.


If you get an error Error: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1081)>


Then update the send_email.py script to below

import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

import ssl
import certifi

# Force Python's default SSL to use certifi's updated certificate bundle
ssl._create_default_https_context = lambda: ssl.create_default_context(cafile=certifi.where())

def send_notification():
    # 1. Construct the email message
    message = Mail(
        from_email='your_verified_email@example.com', # Must match Step 1
        to_emails='recipient@example.com',
        subject='System Alert: Task Completed Successfully',
        html_content='<strong>Success!</strong> Your background job has finished processing.'
    )

    try:
        # 2. Initialize the client using the environment variable
        sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
        
        # 3. Send the email and capture the response
        response = sg.send(message)
        
        # 4. Output the results
        print(f"Status Code: {response.status_code}")
        print(f"Headers: {response.headers}")
        print("Email dispatched successfully!")
        
    except Exception as e:
        print(f"Error: {e}")

if __name__ == '__main__':
    send_notification()

Best Practices for Production:


  • Use Dynamic Templates: Instead of writing raw HTML in your Python code, use SendGrid's Dynamic Templates to design your emails in their drag-and-drop editor and inject variables via Python.

  • Error Handling: Implement robust logging instead of simple print() statements to track failed deliveries.

  • Async Execution: If you are sending emails within a web framework like Django or Flask, offload the sending process to a background task (using Celery or Redis Queue) so the user doesn't have to wait for the API call to complete.

Comments


bottom of page