In this quickstart, you'll learn how to send your first email using the Twilio SendGrid Mail Send API and Python.
Be sure to perform the following prerequisites to complete this tutorial. You can skip ahead if you've already completed these tasks.
When you sign up for a free SendGrid account, you'll be able to send 100 emails per day forever. For more account options, see our pricing page.
Twilio SendGrid requires customers to enable Two-factor authentication (2FA). You can enable 2FA with SMS or by using the Authy app. See the 2FA section of our authentication documentation for instructions.
Unlike a username and password — credentials that allow access to your full account — an API key is authorized to perform a limited scope of actions. If your API key is compromised, you can also cycle it (delete and create another) without changing your other account credentials.
Visit our API Key documentation for instructions on creating an API key and storing an API key in an environment variable. To complete this tutorial, you can create a Restricted Access API key with Mail Send > Full Access permissions only, which will allow you to send email and schedule emails to be sent later. You can edit the permissions assigned to an API key later to work with additional services.
Once your API key is assigned to an environment variable — this quickstart uses SENDGRID_API_KEY
— you can proceed to the next step.
export SENDGRID_API_KEY=<Your API Key>
To ensure our customers maintain the best possible sender reputations and to uphold legitimate sending behavior, we require customers to verify their Sender Identities by completing Domain Authentication. A Sender Identity represents your 'From' email address—the address your recipients see as the sender of your emails.
To get started sending emails with the Python, you may be able to skip Domain Authentication and begin by completing Single Sender Verification. Single Sender Verification is recommended for testing only. Some email providers have DMARC policies that restrict email from being delivered using their domains. For the best experience, please complete Domain Authentication. Domain Authentication is also required to upgrade from a free account.
Before installing Python and sending emails, you can see if you already have a version on your machine.
The Twilio SendGrid Python helper library supports Python 2.7, 3.5, 3.6, 3.7, and 3.8.
Check your Python version by opening your terminal (also known as a command line or console) and typing the following command.
python --version
If you have Python installed, the terminal should print something like the following output.
Python 3.8.5
Though the SendGrid helper library supports Python back to version 2.7, we recommend using a 3.x version now that Python 2 has reached end-of-life status.
It is possible to have multiple versions of Python on your computer. Some operating systems come with a version of Python already installed. If you run python --version
and receive Python 2.7.x
after installing Python 3, try running python3 --version
to see which 3.x version of Python you have installed. This tutorial will use the python
command, assuming you are working with Python 3. If you have not set up Python 3 in a virtual environment, you may need to run the command python3
instead.
For more about running multiple versions of Python, see "Virtual Environments and Packages" in the Python documentation.
If you do not already have a version of Python installed, visit the Python website to download and install a version appropriate for your operating system.
Using a Twilio SendGrid helper library is the fastest way to deliver your first email.
Start by creating a project folder for this app. You can name the project anything you like. We use sg_quickstart
in the following examples.
mkdir sg_quickstart
Next, navigate into the sg_quickstart directory where you will complete the rest of the tutorial.
cd sg_quickstart
The pip package manager was included when you installed Python. You can use pip to install the Twilio SendGrid helper library and save it as a project dependency. If you want to verify that pip is installed, you can type the following into the terminal.
pip --version
The terminal should print something like the following output.
pip 20.1.1 from /usr/locallib/python3.8/site-packages/pip (python 3.8)
If you do not have a version of pip installed, you can download and install it using the pip installation instructions on python.org.
To install the Twilio SendGrid helper library, type the following command into the terminal.
pip install sendgrid
The terminal should print something like.
1Collecting sendgrid2Using cached sendgrid-6.4.6-py3-none-any.whl (73 kB)3Requirement already satisfied: python-http-client>=3.2.1 in /usr/local/lib/python3.8/site-packages (from sendgrid) (3.3.1)4Requirement already satisfied: starkbank-ecdsa>=1.0.0 in /usr/local/lib/python3.8/site-packages (from sendgrid) (1.0.0)5Installing collected packages: sendgrid6Successfully installed sendgrid-6.4.6
You're now ready to write some code and send emails with Python. First, create a file in your project directory. You can use app.py
.
The following Python block contains all the code needed to successfully deliver a message with the SendGrid Mail Send API. You can copy this code, modify the from_email
and to_email
variables, and run the code if you like. We'll break down each piece of this code in the following sections.
1import sendgrid2import os3from sendgrid.helpers.mail import Mail, Email, To, Content45sg = sendgrid.SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY'))6from_email = Email("test@example.com") # Change to your verified sender7to_email = To("test@example.com") # Change to your recipient8subject = "Sending with SendGrid is Fun"9content = Content("text/plain", "and easy to do anywhere, even with Python")10mail = Mail(from_email, to_email, subject, content)1112# Get a JSON-ready representation of the Mail object13mail_json = mail.get()1415# Send an HTTP POST request to /mail/send16response = sg.client.mail.send.post(request_body=mail_json)17print(response.status_code)18print(response.headers)
Your API call must have the following components:
https://api.sendgrid.com/v3/
)
POST
or
PUT
, you must submit your request body in JSON format)
In your app.py
file, import the SendGrid helper library. The library will handle setting the Host, https://api.sendgrid.com/v3/
, for you.
import sendgrid
Next, use the API key you set up earlier. Remember, the API key is stored in an environment variable, so you can use the os.environ.get()
method to access it. This means we also need to import Python's os library.
import os
Assign the key to a variable named sg
using the helper library's SendGridAPIClient()
method. The helper library will pass your key to the v3 API in an Authorization header using Bearer token authentication.
sg = sendgrid.SendGridAPIClient(api_key = os.environ.get('SENDGRID_API_KEY'))
Now you're ready to set up the from_email
, to_email
, subject
, and message body content
. These values are passed to the API in a "personalizations" object when using the v3 Mail Send API. You can assign each of these values to variables, and the SendGrid library will handle creating a personalizations object for you.
First, import the library's Mail
, Email
, To
, and Content
classes.
from sendgrid.helpers.mail import Mail, Email, To, Content
With the helpers imported, define and assign values for from_email
, to_email
, subject
, and content
variables. Assigning an email address like from_email = "sender@example.com"
will work. However, the constructors imported in the previous step allow you to pass data to them to be sure your final message is formatted properly. Be sure to assign the to_email
to an address with an inbox you can access.
Note that the Content()
helper takes two arguments: the content type and the content itself. You have two options for the content type: text/plain
or text/html
. The second parameter will take 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 SendGrid is Fun"4content = Content("text/plain", "and easy to do anywhere, even with Python")
To properly construct the message, pass each of the previous variables into the SendGrid library's Mail constructor. You can assign this to a variable named mail
. You can then use the Mail constructor's get()
method to get a JSON-ready representation of the Mail object.
1mail = Mail(from_email, to_email, subject, content)23# Get a JSON-ready representation of the Mail object4mail_json = mail.get()
Lastly, you need to make a request to the SendGrid Mail Send API to deliver your message.
The helper library uses SendGrid's python-http-client library to construct the request URL by chaining together portions of your desired path. The path to the SendGrid v3 Mail Send endpoint is https://api.sendgrid.com/v3/mail/send
. The helper library sets the client for you, so the https://api.sendgrid.com/v3
portion is taken care of by typing sg.client
. The next parts of the path are /mail
and /send
. You can chain the words mail
and send
onto client
to build the rest of the URL.
With the URL built, python-http-client then allows you to chain on the type of HTTP request you wish to make with a method matching the name of the HTTP verb appropriate for your desired endpoint. To send a message, you should make an HTTP POST
request, so you can use post()
. The post()
method takes a request_body
, which you should set to the JSON version of your message (remember, this JSON-ready version is stored in the mail_json
variable). You can assign this full call to a variable named response
and print the response status code and headers.
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)
With all this code in place, you can run your app.py
file with Python to send the email.
python app.py
If you receive a 202
status code printed to the console, your message was sent successfully. Check the inbox of the “to_email”
address, and you should see your demo message.
If you don't see the email, you may need to check your spam folder.
If you receive an error message, you can reference our response message documentation for clues about what may have gone wrong.
All responses are returned in JSON format. We specify this by sending the Content-Type
header. The Web API v3 provides a selection of response codes, content-type headers, and pagination options to help you interpret the responses to your API requests.
Get additional onboarding support to send better emails with Python. Save time, increase the quality of your sending, and feel confident you are set up for long-term success with SendGrid Onboarding Services.
This is just the beginning of what you can do with our APIs. To learn more, check the resources below.