Last modified: Oct 10, 2026

How to Install SendGrid in Python

SendGrid is a cloud-based email delivery service. It powers transactional and marketing emails for thousands of applications. Python developers use it to send welcome messages, password resets, invoices, and notifications.

This guide walks you through installing SendGrid in Python from scratch. You will learn the prerequisites, the exact pip command, how to set up your API key, and how to send your first email.

By the end, you will have a working setup and the confidence to integrate email into any Python project.

What is SendGrid?

SendGrid is an email API and SMTP relay service. It handles deliverability, scaling, and analytics for you. You focus on your application logic while SendGrid ensures your emails reach inboxes.

The official Python library is called sendgrid. It wraps the SendGrid Web API v3 into simple Python classes. You do not need to build HTTP requests manually. The library handles authentication, JSON formatting, and error parsing.

SendGrid offers a free tier with 100 emails per day. That is enough for development, testing, and small projects.

Prerequisites Before You Install

Before running any install command, confirm your environment is ready.

You need Python 3.7 or newer. Check your version with the following command.

 python --version 
 Python 3.12.3 

On some systems, the command is python3 instead of python. Use whichever one works on your machine.

You also need pip, the Python package installer. Verify it is available.

 pip --version 
 pip 24.0 from /usr/lib/python3/dist-packages/pip (python 3.12) 

Finally, you need a SendGrid account and an API key. Sign up for free at sendgrid.com. Then create an API key with Mail Send Full Access permissions.

If you are already familiar with installing Python packages, such as when you needed to install ReportLab in Python, the process will feel very similar.

Install SendGrid with pip

The installation is a single command. Run this in your terminal.

 pip install sendgrid 

Pip downloads the library and its dependencies. The two main dependencies are python-http-client and cryptography. Both are installed automatically.

 Collecting sendgrid Downloading sendgrid-6.12.5-py3-none-any.whl (85 kB) Collecting python-http-client Downloading python_http_client-3.3.7-py3-none-any.whl (12 kB) Collecting cryptography Downloading cryptography-42.0.5-cp312-cp312-manylinux_2_28_x86_64.whl (4.1 MB) Successfully installed cryptography-42.0.5 python-http-client-3.3.7 sendgrid-6.12.5 

Always work inside a virtual environment when installing Python packages. This keeps your project dependencies isolated and prevents conflicts with system tools.

Use a Virtual Environment

Create a virtual environment with the built-in venv module. Then activate it before installing anything.

 python -m venv sendgrid-env source sendgrid-env/bin/activate 

On Windows, the activation command is different.

 sendgrid-env\Scripts\activate 

Once activated, your prompt shows the environment name. Any package you install now stays inside that folder.

 (sendgrid-env) $ pip install sendgrid 

Best practice: Create a requirements.txt file so others can reproduce your setup with a single command.

 pip freeze > requirements.txt pip install -r requirements.txt 

Set Up Your API Key Securely

Never hardcode your API key in your source code. Instead, store it in an environment variable. This keeps secrets out of version control and deployment logs.

On macOS or Linux, set the variable temporarily in your terminal session.

 export SENDGRID_API_KEY='your_api_key_here' 

On Windows, use the set command for a temporary session.

 set SENDGRID_API_KEY=your_api_key_here 

For permanent storage, add the export line to your shell profile such as .bashrc or .zshrc. Alternatively, use a .env file with the python-dotenv library.

 pip install python-dotenv 
 from dotenv import load_dotenv import os # Load environment variables from .env file load_dotenv() api_key = os.environ.get('SENDGRID_API_KEY') 

This approach works well in development and production alike.

Verify the Installation

Confirm everything works by importing the library in a Python shell.

 import sendgrid from sendgrid.helpers.mail import Mail print(sendgrid.__version__) 
 6.12.5 

No error means the installation succeeded. If you see an ImportError, jump to the troubleshooting section below.

Send Your First Email

The Mail() helper builds your message. The SendGridAPIClient() class handles authentication and sending.

Here is a complete example that sends an HTML email.

 import os from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail # Build the email message message = Mail( from_email='verified@yourdomain.com', to_emails='recipient@example.com', subject='Hello from SendGrid', html_content='This email was sent with Python!' ) # Create the client and send try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e.message) 
 202 b'' Server: nginx 

A status code of 202 means SendGrid accepted the message for delivery. That is the success response.

Important: The from_email address must be a verified sender in your SendGrid account. Unverified senders cause errors.

Sending Attachments

SendGrid supports file attachments. You encode the file in base64 and add it to the message using the Attachment() helper.

 import base64 from sendgrid.helpers.mail import Attachment, FileContent, FileName, FileType, Disposition # Read and encode the file with open('report.pdf', 'rb') as f: data = f.read() encoded = base64.b64encode(data).decode() # Create the attachment object attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.file_name = FileName('report.pdf') attachment.file_type = FileType('application/pdf') attachment.disposition = Disposition('attachment') # Add to your Mail object message.attachment = attachment 

This is useful for invoices, reports, and any document your users need. If you generate PDFs in Python, you can create the file first and then attach it directly. For the full walkthrough on building PDFs, see this guide to generate PDFs with ReportLab.

Using Dynamic Templates

Dynamic templates let you design emails in the SendGrid dashboard and fill them with data from your code. This separates design from logic.

Each template has an ID that starts with d-. You pass that ID and a dictionary of dynamic data.

 message = Mail( from_email='verified@yourdomain.com', to_emails='customer@example.com', subject='Your Order is Ready' ) message.template_id = 'd-abc123def456' message.dynamic_template_data = { 'customer_name': 'Jane', 'order_id': 'ORD-2024-001', 'total': '$49.99' } 

Dynamic templates use Handlebars syntax. You can include conditionals, loops, and fallback values. This makes them powerful for personalized emails at scale.

Common Errors and Troubleshooting

ImportError: No module named 'sendgrid' means the package is not installed in the current environment. Activate your virtual environment and run pip install again.

401 Unauthorized is the most common error. It usually means your API key is invalid, missing, or lacks the Mail Send permission. Double-check that the environment variable is set correctly.

403 Forbidden means your sender email is not verified. Go to the SendGrid dashboard and verify the from address.

400 Bad Request often means a required field is missing. Check that from_email, to_emails, subject, and content are all set.

Quota exceeded on the free tier returns a 401 error in the Python SDK. This is misleading. Check your daily sending limits in the SendGrid dashboard.

Permission denied on Linux or macOS during install means you are installing globally. Use a virtual environment instead.

Best Practices

Always verify your sender domain. Domain authentication improves deliverability and prevents spoofing.

Use environment variables for API keys. Never commit secrets to Git.

Handle exceptions around the send call. Network issues and API limits happen. Your application should degrade gracefully.

Monitor your SendGrid activity feed. It shows delivered, bounced, and dropped messages.

Use dynamic templates for recurring emails. They keep design separate from code and make updates easy.

Keep an eye on rate limits. SendGrid is generous but not infinite. Batch sends when possible.

If your email workflow involves reading incoming PDF documents, you may also want to install pdfplumber in Python to extract text and tables before summarizing them in a notification email.

Conclusion

Installing SendGrid in Python is a quick and straightforward process. Use pip install sendgrid to get the library. Store your API key in an environment variable. Then build messages with the Mail() helper and send them with SendGridAPIClient().

The library handles authentication, JSON formatting, and error parsing for you. You focus on your email content and recipient logic.

Start with a simple HTML email. Then explore attachments, dynamic templates, and scheduling. SendGrid scales from a weekend project to millions of messages per day.

Follow the examples in this guide, and you will have reliable email delivery in your Python application within minutes. Happy coding!