Sending Email Attachments with Twilio SendGrid and Python

November 27, 2019
Written by

Sending Email with Attachments using SendGrid and Python

You're sending emails from your Python app with the Twilio SendGrid API and you want to attach files to your emails? The Twilio SendGrid API makes it very straightforward to include attachments to your emails. In this post, we’ll attach a pdf document to an email sent via SendGrid. If you have not sent your first email with SendGrid, my colleague Sam has written a post about it. We’ll be picking up where that post ended.

Prerequisites

Before we begin, make sure you have the following setup:

Setup

If you haven’t done so already, sign up for a free SendGrid account. You can use the free tier for Ithis tutorial. Once you have your account, create an API Key. You can call it whatever you want, but make sure to hold on to it for later.

Create Api Key with Twilio SendGrid

It should look like this.

Created Api Key with Twilio SendGrid

A good way to save this API key is to set it as an environment variable that you can access from your Python code in order to avoid writing it directly in your code. Set the value of the SENDGRID_API_KEY environment variable to be the API key from your SendGrid account. Here's a useful tutorial if you need help setting environment variables. We will use this later on.

Virtual Environment

You may want to run the code from this post in an isolated Python environment. If you aren’t sure what a virtual environment is here is a post about virtual environments. Here’s how to set it up.

First install the virtualenv package and run the following command:

virtualenv emails

Next  activate the virtual environment:

source ./emails/bin/activate

Install the SendGrid Python helper library in the virtualenv:

pip install sendgrid

Sending an Email

Let’s pick up where my colleague’s blog post left off, sending an email. You should have a send_email.py file that looks like this:

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

message = Mail(
    from_email='from_email@example.com',
    to_emails='to@example.com',
    subject='Sending with Twilio SendGrid is Fun',
    html_content='<strong>and easy to do anywhere, even with Python</strong>')

sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
response = sg.send(message)
print(response.status_code, response.body, response.headers)

We’ll be using the Python base64 module to read our file and encode it as a base64 string. I have used the fictional attachment.pdf file, so make sure to replace the name of the file with a document that you have stored in the same folder as your send_email.py file.

We can create an attachment using the Twilio SendGrid helper libraries. For now let’s send a single attachment.pdf.

hl_lines="2 5 13 14 15 16  18 19 20 21 22 23"
import os
import base64

from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import (Mail, Attachment, FileContent, FileName, FileType, Disposition)


message = Mail(
    from_email='from_email@example.com',
    to_emails='to@example.com',
    subject='Sending with Twilio SendGrid is Fun',
    html_content='<strong>and easy to do anywhere, even with Python</strong>'
)

with open('attachment.pdf', 'rb') as f:
    data = f.read()
    f.close()
encoded_file = base64.b64encode(data).decode()

attachedFile = Attachment(
    FileContent(encoded_file),
    FileName('attachment.pdf'),
    FileType('application/pdf'),
    Disposition('attachment')
)
message.attachment = attachedFile

sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
response = sg.send(message)
print(response.status_code, response.body, response.headers)

Before running this code, make sure you have the SENDGRID_API_KEY environment variable set, and remember to replace the to_emails value with your own email address to verify that your code worked correctly.

Finally, save your code and then in your terminal run the following command to send yourself an email:

python send_email.py

Check your inbox and you should see something like this!

Email with attachment in inbox

 

Wrapping Up

Now you can add attachments to the emails you send with Twilio SendGrid, but you can do so much more! You can check out the SendGrid docs for a ton of other cool features and uses.

 

Feel free to reach out to me with any questions or to talk about the amazing things you are building. I can’t wait to see what you build!

 

  • Twitter: @ChatterboxCoder
  • Instagram: @ChatterboxCoder
  • Email: nokenwa@twilio.com