How to send emails with the Nylas Python SDK

6 min read

By sending emails with Python using the Nylas Connectivity APIs we can be sure that messages land in the recipient’s inbox and not the spam folder. Emails sent with Nylas will look the same as any other email sent from the sender’s account, but we will have API-level control over the message creation and sending.

To make things even easier for Python developers, we offer the Nylas Python SDK. Today we’re going to review how to send emails and attachments with Python using the SDK.

Installing Python

Chances are that we already have Python installed on our machines. We can check the version by doing the following:

$ python3 --version

Python 3.8.9

Note that we can use Python 2.x as well, although moving to Python 3 is recommended.

If we don’t happen to have Python installed, we can use any of these installation methods depending on our operating system.

Creating a virtual environment

Before we move on, we will create a Virtual Environment as it will create a separate “environment” with its own dependencies and packages. This is important because sometimes we might need different package versions for different projects. A Virtual Environment makes this possible.

If we’re using Python 2, then we need to install virtualenv from the pip package manager (if we’re using Python 3 we have it installed already):

# Python 2 users only
$ pip install virtualenv

Now, we create a folder for our project like this:

$ mkdir nylas_python && cd nylas_python

Then, create the Virtual Environment:

# Python 2
$ virtualenv env

# Python 3
$ python3 -m venv env 

This will create a series of subdirectories within our nylas_python directory with this structure:

env/
|__ bin
|__ include
|__ lib
|__ pyenv.cfg

We can now activate our Virtual Environment like this:

$ source env/bin/activate

We can easily deactivate it like this:

$ deactivate

But let’s keep it active and go on to install the Nylas Python SDK.

Installing the Nylas Python SDK

We can get the Nylas Python SDK package from the pip3 package manager like this:

$ pip3 install nylas

You can verify that the Nylas package was installed at this path: nylas_python/env/lib/python3.8/site-packages/nylas

Now we’re ready to grab our Nylas tokens.

Storing our Nylas tokens

Let’s go to the Nylas Dashboard (creating a new account if necessary) and get our CLIENT_ID, CLIENT_SECRET, and ACCESS_TOKEN.

App Setting on the Dashboard

If we go to App Settings on the left-side menu, we will find a “Developer Details” section. The CLIENT_ID and CLIENT_SECRET, our Nylas account credentials, are there.

For the connected user account’s ACCESS_TOKEN, we can go to Accounts in the left-side menu, select our account, and then press “Generate New Token”. This will generate a new token for the connected account, allowing us to take actions on the user’s behalf via API.

We now need to store all of our tokens in a safe way in our local project. For that, we’re going to install a package called python-dotenv which will help us store environment variables that can be accessed by our code:

$ pip3 install python-dotenv

In the root folder where our scripts are going to live (nylas_python/env), we need to create a new file for environment variables. For that we’ll use nano, a terminal-based text editor:

$ nano .env

With the file created and opened, we enter the following into the file:

CLIENT_ID = "<CLIENT_ID>"
CLIENT_SECRET = "<CLIENT_SECRET>"
ACCESS_TOKEN = "<ACCESS_TOKEN>"

Then CTRL+O to save and CTRL+X to exit nano.

Note that you should never commit your .env file or tokens to source control like git or services like GitHub.

Sending emails with Python

Now we get to write some code! For my code editor, I’m going to use Geany; however, you can use the IDE of your choice.

I called this file SendEmail.py:

# Load your env variables
from dotenv import load_dotenv
load_dotenv()

# Import your dependencies
import os
from nylas import APIClient

# Initialize your Nylas API client
nylas = APIClient(
    os.environ.get("CLIENT_ID"),
    os.environ.get("CLIENT_SECRET"),
    os.environ.get("ACCESS_TOKEN"),
)

# Draft your email
draft = nylas.drafts.create()
draft.subject = "With Love, from Nylas"
draft.body = "This email was sent using the Python SDK for the  Nylas Email API. Visit https://www.nylas.com for details."
draft.to = [{"name": "Blag", "email": "[email protected]"}]

# Send your email!
draft.send()

We can run this script from the terminal by using:

$ python3 SendEmail.py

If everything worked fine, then we can simply open the recipient’s email inbox and read the email we just sent from the Nylas SDK:

Reading one of the emails that we just sent

We’ve sent our first email using Python!

Sending Emails with Attachments using Python

Just like we can easily send an email, we can add attachments simply as well.

See the new section in the code below under the Create your attachment comment. Note that, in this example, you’ll need an image named "PythonLogo.png" stored in the same folder as your code. (If you want to use the Python logo, you can get it here.)

I called this file SendEmailAttachment.py:

# Load your env variables
from dotenv import load_dotenv
load_dotenv()

# Import your dependencies
import os
from nylas import APIClient

# Initialize your Nylas API client
nylas = APIClient(
    os.environ.get("CLIENT_ID"),
    os.environ.get("CLIENT_SECRET"),
    os.environ.get("ACCESS_TOKEN"),
)

# Create your attachment
attachment = open("PythonLogo.png", "rb")
attach = nylas.files.create()
attach.filename = 'PythonLogo.png'
attach.stream = attachment

# Draft your email and attach your file
draft = nylas.drafts.create()
draft.subject = "Python with Attachment"
draft.body = "This email was sent using the Python SDK for the Nylas Email API. Visit https://www.nylas.com for details."
draft.to = [{"name": "Blag", "email": "[email protected]"}]
draft.attach(attach)

# Send your email!
draft.send()
attachment.close()

We can run this script by using:

$ python3 SendEmailAttachment.py

If everything worked fine, then we can simply open the recipient’s email inbox and read the received email:

Reading the email with attachment that we just sent

And that’s it! As you can see, by using the Nylas Python SDK, sending emails becomes an easy task. If you want to learn more, visit our Documentation Page.

You can sign up Nylas for free and start building!

Don’t miss the action, watch our LiveStream Coding with Nylas:

Join our technical demo to see the Nylas Platform in action

Related resources

How to customize the Nylas Scheduler workflow with custom events

We’re excited to announce the launch of the Nylas Scheduler v3! Efficient scheduling is essential…

How to block time slots in Outlook and Google calendar with Nylas Calendar API

Key Takeaways Managing calendar availability is essential for professionals, teams, and businesses to stay organized…

How to Solve Webhook Integration Challenges with PubSub Notification Channel

Key Takeaways This article addresses the challenges of webhook integration and introduces the PubSub Notification…