Only show these results:

Python SDK

The Nylas Communications Platform allows developers to quickly build features that connect to every inbox, calendar, and contacts book in the world. The Nylas SDKs are the quickest way to integrate the Nylas Email, Calendar, and Contacts APIs into your app.

This guide will help you get started with the Nylas Python SDK.

Prerequisites

Before you install the SDK, sign up for a Nylas developer account, and follow our guide to get your developer API keys. You will need 3 values from this guide to run the code examples found here:

  • CLIENT_ID - The CLIENT ID found on the dashboard page for your Nylas App
  • CLIENT_SECRET - The CLIENT SECRET found on the dashboard page for your Nylas App
  • ACCESS_TOKEN - The Access token that is provided when you authenticate an account to your Nylas App

You will also need to:

Install the Nylas Python SDK

With your virtual environment activated, run

pip install nylas

Congrats! You’re now ready to write code with the Nylas Python SDK.

Initialize the API Client

There are 2 ways to initialize APIClient:

  • Nylas App
  • Individual user account

Create Nylas App Client

A Nylas App client allows you to access and modify the Account Management endpoint, which lets you check the status of user accounts connected to your Nylas app and upgrade/downgrade them. To create a Nylas App client object, initialize an APIClientobject, passing only the CLIENT_ID and CLIENT_SECRET for your Nylas app.

from nylas import APIClient

nylas = APIClient(
CLIENT_ID,
CLIENT_SECRET,
)


accounts = nylas.accounts.all()
for account in accounts:
print("Email: {} | Billing State: {} | Sync State: {} | Account ID: {}".format(
account.get('email'), account.get('billing_state'),
account.get('sync_state'), account.get('account_id')
))

Create Nylas User Account Client

A Nylas account client object lets you access all email, calendar, and contacts functionality and data for a specific user account. To create a Nylas account client object, initialize an APIClient object, passing the CLIENT_ID and CLIENT_SECRET for your Nylas App and the ACCESS_TOKENfor the specific user account.

from nylas import APIClient

nylas = APIClient(
CLIENT_ID,
CLIENT_SECRET,
ACCESS_TOKEN
)

account = nylas.account
print('Email: {} | Provider: {} | Organization: {}'.format(
account.email_address, account.provider, account.organization_unit
))

Learn More

Read the API reference for the accounts endpoint to learn more about the information you can access for accounts. Now, you should be ready to take a look at how to use the Nylas Python SDK to leverage the Nylas email, calendar, and contacts APIs.

Email

The Nylas Email API makes it easy to integrate Gmail, Outlook, Microsoft Exchange, Office 365 and every other email service provider into your application, and it offers full Create, Read, Update, and Delete (CRUD) operations.

The Nylas Email API allows you to work with both messages and threads.

View Email Messages and Threads

Messages are the fundamental object of the Nylas platform, and the core building block for most email applications. They contain several pieces of information, such as when a message was sent, the sender's address, to whom it was sent, and the message body. They can also contain files (attachments), calendar event invitations, and more.

Threads arefirst-classobjects that represent a collection of messages. Messages are threaded together with a variety of heuristics to match the format of third-party accounts as close as possible.

from nylas import APIClient

nylas = APIClient(
CLIENT_ID,
CLIENT_SECRET,
ACCESS_TOKEN,
)


message = nylas.messages.first()
print("Subject: {} | Unread: {} | from: {} | ID: {}".format(
message.subject, message.unread, message.from_, message.id
))


threads = nylas.threads.all(limit=10)
for thread in threads:
print("Subject: {} | Participants: {}".format(
thread.subject, thread.participants
)
)

for thread in nylas.threads.where(unread=True, limit=5):
print(thread.subject)

Learn More

View the API reference for messages and threads to learn more. You can also check out the email API quickstart guide to learn more about the functionality of the Nylas Email API. Take a look at our tutorial to Read an Email Inbox With Python for more on viewing messages and threads.

Search Messages and Threads

The search sub-endpoint is used to run a full-text search, that is proxied to the account's provider. Results are matched with objects that have been synced, and then returned.

from nylas import APIClient

nylas = APIClient(
CLIENT_ID,
CLIENT_SECRET,
ACCESS_TOKEN,
)


message = nylas.messages.search("from:swag@nylas.com")
print(message.subject)


thread = nylas.threads.search("to:swag@nylas.com")
print(thread.subject)

Learn More

View the API reference for messages and threads to learn more. You can also check out the email API quickstart guide to learn more about the functionality of the Nylas Email API.

Check out our tutorial to send an email with Python.

Send an Email

from nylas import APIClient

nylas = APIClient(
CLIENT_ID,
CLIENT_SECRET,
ACCESS_TOKEN,
)

draft = nylas.drafts.create()
draft.subject = "With Love, from Nylas"
draft.body = "This email was sent using the Nylas Email API. Visit https://nylas.com for details."
draft.to = [{'name': 'My Nylas Friend', 'email': 'swag@nylas.com'}]

draft.send()

Reply to an Email

from nylas import APIClient
nylas = APIClient(
CLIENT_ID,
CLIENT_SECRET,
ACCESS_TOKEN
)

thread = nylas.threads.get('{id}')
draft = thread.create_reply()
draft.body = "This is my reply"
draft.send()


message = nylas.messages.get('{id}')
draft = nylas.drafts.create()
draft.reply_to_message_id = message.id
draft.body = "This is my reply"
draft.to = message.from_
draft.send()

Attach a File to an Email

from nylas import APIClient
nylas = APIClient(
CLIENT_ID,
CLIENT_SECRET,
ACCESS_TOKEN
)


attachment = open('attachment.pdf', 'r')
file = nylas.files.create()
file.filename = 'attachment.pdf'
file.stream = attachment

file.save()
attachment.close()


draft = nylas.drafts.create()
draft.subject = "With Love, From Nylas"
draft.body = 'This email was sent using the Nylas Email API. Visit https://nylas.com for details.'
draft.to = [{'name': 'My Nylas Friend', 'email': 'swag@nylas.com'}]
draft.attach(file)
draft.send()

Learn More

View the API reference for sending to learn more. You can also check out the email API quickstart guide to learn more about the functionality of the Nylas Email API.

Take a look at our tutorial on managing inbox folders and labels

Organize Inboxes with Folders and Labels

from nylas import APIClient
nylas = APIClient(
CLIENT_ID,
CLIENT_SECRET,
ACCESS_TOKEN
)


if nylas.account.organization_unit == 'label':

labels = nylas.labels.all()

print("This account has the following labels")
for label in labels:
print("Name: {} | ID: {}".format(label.display_name, label.id))

label = nylas.labels.create()
label.display_name = "My Label"
label.save()

message = nylas.messages.first()
message.add_label(label.id)


elif nylas.account.organization_unit == 'folder':

folders = nylas.folders.all()

print("This account has the following folders")
for folder in folders:
print("Name: {} | ID: {}".format(folder.display_name, folder.id))

folder = nylas.folders.create()
folder.display_name = 'My Folder'
folder.save()

thread = nylas.threads.first()
thread.update_folder(folder.id)

Calendar API

The Nylas Calendar API acts as a layer of abstraction on top of all calendar providers. The Nylas calendar API offers full Create, Read, Update, and Delete (CRUD) operations for all major calendar providers, with just a few lines of code you can add full-featured scheduling & calendar sync to your application.

Read Calendars and Events

from nylas import APIClient
nylas = APIClient(
CLIENT_ID,
CLIENT_SECRET,
ACCESS_TOKEN
)


calendars = nylas.calendars.all()
for calendar in calendars:

print("Name: {} | Description: {} | Read Only: {}".format(
calendar.name, calendar.description, calendar.read_only))



calendar = nylas.calendars.first()

events = nylas.events.where(calendar_id=calendar.id).all(limit=5)
for event in events:
print("Title: {} | When: {} | Participants: {}".format(
event.title, event.when, event.participants
))

Learn More

Check out the API reference docs for calendars and events to learn more about the features of these endpoints. You can also take a look at the calendar API quickstart guide to learn more about the functionality of the Nylas calendar API.

For details on how this example works, check out our tutorial on creating calendar events with Python.

Create an Event

from nylas import APIClient

nylas = APIClient(
CLIENT_ID,
CLIENT_SECRET,
ACCESS_TOKEN,
)


event = nylas.events.create()
event.title = "New Years Party!"
event.location = "My House!"

event.when = {"start_time": 1546290000, "end_time": 1546300800}


event.participants = [{"name": "My Nylas Friend", 'email': 'swag@nylas.com'}]


event.calendar_id = CALENDAR_ID



event.save(notify_participants=True)

Learn More

Check out the API reference docs for calendars and events to learn more about the features of these endpoints. You can also take a look at the calendar API quickstart guide to learn more about the functionality of the Nylas calendar API.

Contacts API

The Nylas Contacts API connects address books and contact databases associated with users' email accounts directly into your application. It offers full Create, Read, Update, and Delete (CRUD) operations to perform bi-directional sync with contact data including addresses, email addresses, birthdays, job titles, and more.

Read Contact Information

from nylas import APIClient

nylas = APIClient(
APP_ID,
APP_SECRET,
ACCESS_TOKEN,
)

contacts = nylas.contacts.all(limit=10)
for contact in contacts:



email = list(contact.emails.values())[0][0]

print("Name: {} {} | Email: {} | ID: {}".format(
contact.given_name, contact.surname, email, contact.id)
)

Create and Modify Contacts

from nylas import APIClient

nylas = APIClient(
CLIENT_ID,
CLIENT_SECRET,
ACCESS_TOKEN,
)

contact = nylas.contacts.create()
contact.given_name = "My Nylas Friend"
contact.emails['work'] = ['swag@nylas.com']
contact.notes = "Make sure to keep in touch!"
contact.web_pages['homepage'] = ['https://nylas.com']
contact.save()

Learn More

Check out the API reference docs for the contacts endpoint to learn more. You can also take a look at the contacts API quickstart guide to learn more about the functionality of the Nylas contacts API.

Create a New Contact

from nylas import APIClient

nylas = APIClient(
APP_ID,
APP_SECRET,
ACCESS_TOKEN,
)

contact = nylas.contacts.create()


contact.given_name = "My Nylas Friend"


contact.emails['work'] = ['swag@nylas.com']
contact.notes = "Make sure to keep in touch!"




contact.phone_numbers['business'] = ['(555) 555-5555']


contact.web_pages['homepage'] = ["https://nylas.com"]

contact.save()

Learn More

Check out the API reference docs for the contacts endpoint to learn more. You can also take a look at the contacts API quickstart guide to learn more about the functionality of the Nylas contacts API.

Additional Functionality

The Python SDK GitHub repo contains a number of useful examples in the examples directory that demonstrate how to handle things like webhooks, native authentication for Gmail and Exchange, and hosted OAuth.

Authentication

The Nylas REST API uses server-side (three-legged) OAuth, and this library provides convenience methods to simplify the OAuth process. Here's how it works:

  • You redirect the user to our login page, along with your App Id and Secret
  • Your user logs in
  • They are redirected to a callback URL of your own, along with an access code
  • You use this access code to get an authorization token to the API
  • For more information about authenticating with Nylas, check our the API Reference for Authentication.

In practice, the Nylas REST API client simplifies this down to two steps.

Step 1: Redirect the User to Nylas

from flask import Flask, session, request, redirect, Response
from nylas import APIClient

@app.route('/')
def index():
redirect_url = "http://0.0.0.0:8888/login_callback"
client = APIClient(APP_ID, APP_SECRET)
return redirect(client.authentication_url(redirect_url, scopes='email.read_only,email.send'))

The Nylas API provides granular authentication scopes that empower users with control over what level of access your application has to their data. Pass a comma-separated string of scopes to the scopes argument for theauthentication_url method. See supported authentication scopes for a full list of scopes and details behind the scopes.

Step 2: Handle the Authentication Response

@app.route('/login_callback')
def login_callback():
if 'error' in request.args:
return "Login error: {0}".format(request.args['error'])


client = APIClient(APP_ID, APP_SECRET)
code = request.args.get('code')
session['access_token'] = client.token_for_code(code)

You can also use an OAuth library to simplify the authentication flow, such as Python Social Auth or Flask-Dance. This SDK also includes an example project that demonstrates how to implement OAuth.

Message Tracking Features

If you have webhooks enabled for your developer application you can access Nylas' Message Tracking Features to see when a recipient opens, replies, or clicks links within a message.

draft = client.drafts.create()
draft.to = [{'name': 'My Nylas Friend', 'email': 'swag@gmail.com'}]
draft.subject = "Python SDK link tracking"
draft.body = "This email was sent using the Nylas Email API"
draft.tracking = { 'links': 'false', 'opens': 'true', 'thread_replies': 'true', 'payload':'python sdk open tracking test' }
draft.send()

It’s important to remember that you must wrap links in<a>tags for them to be tracked. Most email clients automatically create links from items that look like links, like10.0.0.1,tel:5402502334, or apple.com. For links to be tracked properly, you must create the links before sending the draft.

Additional Resources

Here are some additional resources for when you're ready to move on.

  • Familiarize yourself with the Nylas Communications Platform through our getting started guide
  • Take a look at the quickstart guides for the Nylas Email, Calendar and Contacts APIs to explore the features of the Nylas Communication Platform.
  • Setup Postman to make it easy to explore the Nylas APIs.
  • When you're ready to start integrating the Nylas Communication Platform into your app, take a look at our app integration guide.
  • Finally, you can always take a look at the API reference to learn about how the Nylas APIs work.