Nylas Docs

The Nylas Developer Hub

Welcome to the Nylas developer hub. You'll find comprehensive guides and documentation to help you start working with Nylas as quickly as possible, as well as support if you get stuck. Let's jump right in!

Developer Guide

Python SDK

The Nylas Python SDK Quickstart Guide

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.

Setup your developer account first!

Before following this guide, sign up for a Nylas developer account, and follow our guide to get your developer API keys.

Create Your Developer Account

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 three 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

Install the Nylas Python SDK

Prerequisites

  • Ensure you have pip installed on your development environment.
  • Create a virtual environment to install Nylas.

Refer to the official Python documentation on pip and virtualenv to learn more about how to set this up.

Installing the SDK

With your virtual environment activated, run pip install nylas.

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

Quickstart Examples

Create a Client Object to Connect to Your Nylas App

All of the functionality of the Nylas Communications Platform is available through the APIClient object. There are two ways to initialize APIClient: for a Nylas App, and for an individual user account.

Create Nylas App Client For Account Management
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 APIClient object, passing only the CLIENT_ID and CLIENT_SECRET for your Nylas app.

from nylas import APIClient

nylas = APIClient(
    CLIENT_ID,
    CLIENT_SECRET,
)

# Return all accounts that are connected to your Nylas App
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_TOKEN for 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
))
Ready to Build Your Integration?

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 API

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.

Messages and Threads

The Nylas Email API allows you to work with both 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 are first-class objects 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.

View Email Messages and Threads

Take a look at our tutorial to Read an Email Inbox With Python for more details about this example.

from nylas import APIClient

nylas = APIClient(
    CLIENT_ID,
    CLIENT_SECRET,
    ACCESS_TOKEN,
)

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


# .all() returns all threads that have been synced to Nylas
threads = nylas.threads.all(limit=10) # Limit and offset can be used to control pagination
for thread in threads:
    print("Subject: {} | Participants: {}".format(
        thread.subject, thread.participants
        )
    )

# Filter for the 5 most recent unread threads
for thread in nylas.threads.where(unread=True, limit=5):
    print(thread.subject)
Ready to Build Your Email Integration?

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.

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,
)

# Search for the most recent email from a specific address
message = nylas.messages.search("from:swag@nylas.com")[0]
print(message.subject)

# You can also search threads
thread = nylas.threads.search("to:swag@nylas.com")[0]
print(thread.subject)
Ready to Build Your Email Integration?

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.

Send an Email

For details on how this example works, check out our tutorial to send an email with Python.

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

For details on how this example works, check out our tutorial to send an email with Python.

from nylas import APIClient
nylas = APIClient(
    CLIENT_ID,
    CLIENT_SECRET,
    ACCESS_TOKEN
)
# Send a reply to a thread
thread = nylas.threads.get('{id}')
draft = thread.create_reply()
draft.body = "This is my reply"
draft.send()

# Alternatively, you can send replies by setting reply_to_message_id
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

For details on how this example works, check out our tutorial to send an email with Python.

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

# Create a new file with the stream interface for binary objects
attachment = open('attachment.pdf', 'r')
file = nylas.files.create()
file.filename = 'attachment.pdf'
file.stream = attachment
# .save() saves the file to Nylas, file.id can then be used to attach the file to an email
file.save()
attachment.close()

# Create a new email draft to attach the new file to.
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()
Ready to Build Your Email Integration?

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.

Organize Inboxes with Folders and Labels

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

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

# The organization_unit attribute for the account object lets you know if the account uses folders or labels for organization
# Gmail uses labels, all other providers use folders
# Account object reference: https://docs.nylas.com/reference#account
if nylas.account.organization_unit == 'label': # Gmail uses labels

    # Labels reference: https://docs.nylas.com/reference#labels
    labels = nylas.labels.all()

    # Gmail includes a number of default labels,
    # including Inbox, Important, Trash, Spam, and more
    print("This account has the following labels")
    for label in labels:
        print("Name: {} | ID: {}".format(label.display_name, label.id))

    # New labels must be assigned a display_name before they can be saved
    label = nylas.labels.create()
    label.display_name = "My Label"
    label.save()

    # Now we'll assign this label to the most recent message in the account's inbox
    message = nylas.messages.first()
    message.add_label(label.id)
    # Messages can have multiple labels
    # You can pass a list of id strings to .update_labels() to batch update.
    # Remove the label with message.remove_label(my_label_id)

elif nylas.account.organization_unit == 'folder': # All other providers use folders

    # Folders reference: https://docs.nylas.com/reference#folders
    folders = nylas.folders.all()

    # Microsoft accounts include a number of default folders,
    # including Inbox, Important, Trash, Spam, and more
    print("This account has the following folders")
    for folder in folders:
        print("Name: {} | ID: {}".format(folder.display_name, folder.id))

    # New folders must be assigned a display_name before they can be saved
    folder = nylas.folders.create()
    folder.display_name = 'My Folder'
    folder.save()

    # Now we'll move the most recent email thread to our new folder
    thread = nylas.threads.first()
    thread.update_folder(folder.id)
    # Note: an email message can only be contained in a single folder, but
    # a thread with multiple messages can span multiple folders

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
)

# Most user accounts have multiple calendars where events are stored
calendars = nylas.calendars.all()
for calendar in calendars:
    # Print the name and description of each calendar and whether or not the calendar is read only
    print("Name: {} | Description: {} | Read Only: {}".format(
        calendar.name, calendar.description, calendar.read_only))


# Get the id of a calendar whose events we want to inspect.
calendar = nylas.calendars.first()
# Return the 5 oldest events from a specified calendar and print their titles to the console.
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
    ))
Ready to Build Your Calendar Integration?

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.

Create an Event

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

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 times are set via UTC timestamps
event.when = {"start_time": 1546290000, "end_time": 1546300800}

# Participants can be added via a list of participant subobjects
event.participants = [{"name": "My Nylas Friend", 'email': 'swag@nylas.com'}]

# CALENDAR_ID must be the value of a calendar the user account has write access to.
event.calendar_id = CALENDAR_ID

# Event emails are not sent by default
# Enable notify_participants to send an email notification to participants
event.save(notify_participants=True)
Ready to Build Your Calendar Integration?

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:

    # contact.emails returns a defaultdict() object
    # that contains a list of email addresses with their appropriate labels
    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()
Ready to Build Your Contacts Integration?

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()
# The contact's given name is typically their first name,
# you can specify a last name with 'surname'
contact.given_name = "My Nylas Friend"

# Email address 'type' must be either 'work' or 'personal'
contact.emails['work'] = ['swag@nylas.com']
contact.notes = "Make sure to keep in touch!"

# Phone number type must be one of 'business', 'organization_main',
# 'mobile', 'assistant', 'business_fax', 'home_fax', 'radio', 'car', 'home', or 'pager'
# Google labels 'business' phone numbers as the contact's Work phone number
contact.phone_numbers['business'] = ['(555) 555-5555']

# Web page type must be one of 'homepage', 'profile', 'work', or 'blog'
contact.web_pages['homepage'] = ["https://nylas.com"]

contact.save()
Ready to Build Your Contacts Integration?

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
She is 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 the authentication_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'])

    # Exchange the authorization code for an access token
    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.

# Send a message with tracking enabled
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 note that you must wrap links in <a> tags for them to be tracked. Most email clients automatically “linkify” things that look like links, like 10.0.0.1, tel:5402502334, or apple.com. For links to be tracked properly, you must linkify the content 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.

Python SDK


The Nylas Python SDK Quickstart Guide

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.