send emails with python with sendgrid api

How To Send Emails With SendGrid Using Python

In this post, we’re going to make a Python algorithm to send emails by leveraging SendGrid API. Furthermore, we’re also be going through the process of setting up everything on SendGrid website to make this thing work.

SendGrid makes the process of sending emails with code really simple, because they already have a Python package ready. This means, it’s pretty much plug and play since we just need to input bare minimum information.

Setup

First of all, you’ll need to create a SendGrid account, in case you haven’t done that yet. Once you take care of that, you’ll need to create a sender, from which you’ll be sending your emails via code. You can find this section under Marketing tab and Senders submenu option.

Now, for the most important part of the setup, you’ll need to create an API key. This key will allow us to access SendGrid services with your account authentication inside the code. Furthermore, you can find your API key section under Settings tab and API Keys submenu option.

Next part of the setup process includes the installation of the SendGrid Python package. Following pip command takes care of this part.

pip install sendgrid

Alright, now you’re all set for the coding part of this tutorial.

Send emails with Python

Like with all other Python projects on this blog, the first thing we need to do is import all the necessary libraries and tools.

import os
import json
import sendgrid
from sendgrid.helpers.mail import Email, To, Mail, Content

In the following step, I’ll define a function that will fetch the API key from a json file located in the same directory as the main project file. Reason for this is so we don’t expose the API key inside the project code in case you’ll want to share it with anyone.

ROOT = os.path.dirname(__file__)

def get_token(token_name):
    with open(os.path.join(ROOT, 'auth.json'), 'r') as auth_file:
        auth_data = json.load(auth_file)
        token = auth_data[token_name]
        return token

Alright, next thing we need to do is create an API instance, where we also input our API key. Additionally, we’ll use this instance to send the email later.

sg = sendgrid.SendGridAPIClient(api_key=get_token('sendgrid-token'))

Great! Now, before we try and send anything, we need to create the email first. Furthermore, this part includes inputing the senders and recipients email addresses, and email subject and its contents.

from_email = Email('<senders_email_address>')
to_email = To('<recipients_email_address>')
subject = "Test subject"
content = Content('text/plain', 'I just sent you an email with python.')

mail = Mail(from_email, to_email, subject, content)

And for the final part of this tutorial, we send the email using the following code. In addition, we can also print out the response information from the post request.

response = sg.client.mail.send.post(request_body=mail.get())

if response.status_code == 202:
    print('Email sent successfully.')
else:
    print('Something went wrong.')

Alrighty! Now you should have a new email waiting in the the recipients inbox. In case you can’t see it there though, you should check inside the spam folder.

Here is also the entire code of this project.

import os
import json
import sendgrid
from sendgrid.helpers.mail import Email, To, Mail, Content

ROOT = os.path.dirname(__file__)

def get_token(token_name):
    with open(os.path.join(ROOT, 'auth.json'), 'r') as auth_file:
        auth_data = json.load(auth_file)
        token = auth_data[token_name]
        return token

sg = sendgrid.SendGridAPIClient(api_key=get_token('sendgrid-token'))

from_email = Email('<senders_email_address>')
to_email = To('<recipients_email_address>')
subject = "Test subject"
content = Content('text/plain', 'I just sent you an email with python.')

mail = Mail(from_email, to_email, subject, content)

response = sg.client.mail.send.post(request_body=mail.get())

if response.status_code == 202:
    print('Email sent successfully.')
else:
    print('Something went wrong.')

Conclusion

To conclude, we made a simple Python script that can send emails by utilizing the SendGrid API. I learned a lot while working on this project and I hope you’ll find it helpful as well.

Share this article:

Related posts

Discussion(0)