Email API Quickstart: How to Send Email with Python
Send your first email using the Twilio SendGrid Mail Send API and Python.
Complete the following prerequisites before starting this tutorial. You can skip ahead if you've already completed these tasks.
- Create a Twilio account in the legacy Console.
- Enable two-factor authentication.
- Create and store a Twilio SendGrid API Key with Mail Send > Full Access permissions.
- Complete Domain Authentication.
- Install Python 3.10 or later.
- Install the Twilio SendGrid Python Helper Library. Using pip, run the following command:
pip install sendgrid
An API call requires a resource and an authentication method. To send an email message, the Twilio SendGrid Mail API sends a POST request to the Twilio SendGrid API endpoint and authenticates it with an API key.
To send an email message using Python, build a Python app.
-
Create a file in your project directory. For this guide, name the file
app.py. -
Import the required Python libraries and classes.
- Import the Twilio SendGrid Python library. The library sets the host:
https://api.sendgrid.com/v3/.import sendgrid - Import the Python OS library. As you stored your API key in an environment variable, you need to import the Python
oslibrary.import os - Import the library's
Mail,Email,To, andContentclasses.from sendgrid.helpers.mail import Mail, Email, To, Content - Import the API key from the local environmental variable. Assign the key to a variable named
sgusing the SDK'sSendGridAPIClient()method. The SDK passes your API key to the v3 API in an Authorization header using Bearer token authentication.sg = sendgrid.SendGridAPIClient(api_key = os.environ.get('SENDGRID_API_KEY'))
- Import the Twilio SendGrid Python library. The library sets the host:
-
Define the values for the To and From email addresses and the subject and body of your email message.
- Assign these values to the
from_email,to_email,subject, andcontentvariables. - To properly format your email message, the imported constructors can accept and pass the data to a
personalizationsobject that the Python SDK creates. Assign theto_emailto an email address with an inbox that you can access. - The
Content()helper takes two arguments: the content type and the content itself. Accepted values for the first parameter, content type, includetext/plainortext/html. The second parameter takes the plain text or HTML content you wish to send.
1from_email = Email("test@example.com") # Change to your verified sender2to_email = To("test@example.com") # Change to your recipient3subject = "Sending with Twilio SendGrid is Fun"4content = Content("text/plain", "and easy to do anywhere, even with Python") - Assign these values to the
-
Assign a Twilio SendGrid Python SDK
Mailconstructor to a variable calledmail. Pass each of the previous variables into thisMailconstructor.1# Create and assign a Mail constructor to a variable2mail = Mail(from_email, to_email, subject, content) -
Retrieve a JSON-ready representation of the
Mailobject with the Mail constructor'sget()method.1# Get a JSON-ready representation of the Mail object2mail_json = mail.get() -
To deliver your message, make a
POSTrequest to the Twilio SendGrid Mail Send API. This request passes themail_jsonvalue to the Mail Send resource.1# Send an HTTP POST request to /mail/send2response = sg.client.mail.send.post(request_body=mail_json)3print(response.status_code)4print(response.headers) -
From your command line, run your
app.pyfile. This sends your email message.python app.pyIf you receive a
202status code printed to the command line, Twilio SendGrid succeeded in sending your message. -
Check the inbox of the
to_emailaddress.- Check the inbox of the
to_emailaddress, and you should see your demo message. - If you don't see the email, check your spam folder.
- Check the inbox of the
If you receive an error message, see the Twilio response message documentation for clues about what may have gone wrong.
Twilio SendGrid returns all responses in JSON format. To specify this format, add the Content-Type header. To interpret the responses to your API requests, the Twilio SendGrid API v3 provides a selection of response codes, content-type headers, and pagination options.
To do more with the Twilio SendGrid APIs, see the following resources.