Only show these results:

Get started with the Nylas Python SDK

The Nylas Python SDK is an open-source software development tool kit that enables you to use Python to quickly integrate email, calendar, and contacts data from various providers.

What you'll learn

In this tutorial, you'll learn how to do the following tasks:

  • Install the Nylas Python SDK.
  • Initialize the API object.
  • Change the base API URL.
  • Integrate with the Nylas Email, Calendar, and Contacts APIs.

Prerequisites

  • Sign up for your Nylas developer account.

  • Get your Nylas keys:

    • For v2
      • CLIENT_ID: The client ID for your application in the Nylas Dashboard.
      • CLIENT_SECRET: The client secret for your application in the Nylas Dashboard.
      • ACCESS_TOKEN: The access token provided when you authenticate an account to your Nylas application.
    • For v3
      • NYLAS_API_KEY: The API Key for your application in the Nylas Dashboard.
      • NYLAS_API_URI: The URI for your application as per data residency.
      • GRANT_ID: The grant ID provided when you authenticate an account to your Nylas application.
  • Install pip and create a virtual environment. See the official Python documentation on pip and virtualenv for more information.

Step 1: Install the Nylas Python SDK

Run the following command:

pip install nylas   

Step 2: Initialize the API object

You can initialize the APIClient object for either a Nylas app client or a Nylas user account client:

  • A Nylas app client allows you to access and modify the Application Accounts endpoint, which enables you to check the status of user accounts connected to your Nylas app and upgrade or downgrade them. You need the NYLAS_CLIENT_ID and NYLAS_CLIENT_SECRET parameters to initialize the APIClient object.

    from nylas import APIClient

    nylas = APIClient(
    NYLAS_CLIENT_ID,
    NYLAS_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')
    ))
  • A Nylas user account client enables you to access all Email, Calendar, and Contacts functionality and data for a specific user account. You need the NYLAS_CLIENT_ID, NYLAS_CLIENT_SECRET, and ACCESS_TOKEN parameters for the specific user account to initialize the APIClient object. For more information, you can browse the Accounts API endpoint docs.

    from nylas import APIClient

    nylas = APIClient(
    NYLAS_CLIENT_ID,
    NYLAS_CLIENT_SECRET,
    ACCESS_TOKEN
    )

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

Step 3: (Optional) Change the base API URL

You can choose to change the base API URL depending on your location, as in the table below.

Location Nylas and Scheduler API URL (v3) Nylas API URL (v2) Scheduler API URL (v2)
United States (Oregon) https://api.us.nylas.com https://api.nylas.com https://api.schedule.nylas.com
Europe (Ireland) http://api.eu.nylas.com https://ireland.api.nylas.com https://ireland.api.schedule.nylas.com

For more information, see the data residency documentation and the Migration guide for data centers.

To change the base API URL, do the following:

  • For Nylas v3, pass the API_URI parameter with the API URL of your location.
  • For Nylas v2, pass the API_URL parameter with the API URL of your location.

🔍 The base API URL defaults to the Nylas U.S. region. If you're using the EU region, you can specify api_uri='https://api.eu.nylas.com' (v3) or api_server='https://ireland.api.nylas.com' (v2).

from nylas import APIClient

nylas = APIClient(
NYLAS_CLIENT_ID,
NYLAS_CLIENT_SECRET,
ACCESS_TOKEN,
API_URL
)

Use cases: Email API

The following examples show you how to use the Nylas Python SDK and Email API to perform common tasks.

View messages and threads

Messages are the fundamental object of the Nylas platform and the core building block for most email applications. Messages contain several pieces of information, such as when the 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 collections of messages which are related to each other, and result from people replying to an email conversation. For Gmail and Microsoft Exchange accounts, Nylas threads messages together so that they are as similar as possible to their representation in those environments. For all other providers, including generic IMAP, Nylas threads messages using a custom JWZ-inspired algorithm.

For more information, see the following Nylas API reference documentation:

Theh following example reads messages and threads:

from nylas import APIClient

nylas = APIClient(
NYLAS_CLIENT_ID,
NYLAS_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

Learn more about the Messages and Threads API endpoints.

Search messages and threads

You can use the Search sub-endpoint to run a full-text search that is proxied through the account's provider. Nylas matches the results with objects that is has synced, and returns them.

from nylas import APIClient

nylas = APIClient(
NYLAS_CLIENT_ID,
NYLAS_CLIENT_SECRET,
ACCESS_TOKEN,
)


message = nylas.messages.search("from:[email protected]")
print(message.subject)


thread = nylas.threads.search("to:[email protected]")
print(thread.subject)

Send an email

from nylas import APIClient

nylas = APIClient(
NYLAS_CLIENT_ID,
NYLAS_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': '[email protected]'}]

draft.send()

Reply to an Email

from nylas import APIClient
nylas = APIClient(
NYLAS_CLIENT_ID,
NYLAS_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(
NYLAS_CLIENT_ID,
NYLAS_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': '[email protected]'}]
draft.attach(file)
draft.send()

Learn More

Learn more about the Sending API endpoint.

Organize inboxes with folders and labels

from nylas import APIClient
nylas = APIClient(
NYLAS_CLIENT_ID,
NYLAS_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)

Use cases: Calendar API

The following examples show tasks you can perform using the Nylas Python SDK and Calendar API.

Read calendars and events

from nylas import APIClient
nylas = APIClient(
NYLAS_CLIENT_ID,
NYLAS_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

Learn more about the Calendars and Events API endpoints.

Create an event

from nylas import APIClient

nylas = APIClient(
NYLAS_CLIENT_ID,
NYLAS_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': '[email protected]'}]
event.calendar_id = CALENDAR_ID

event.save(notify_participants=True)

Learn More

Learn more about the Calendars and Events API endpoints.

Use cases: Contacts API

The following example shows you how to use the Nylas Python SDK and Contacts API to create a new contact.

Read contacts

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 contacts

from nylas import APIClient

nylas = APIClient(
NYLAS_CLIENT_ID,
NYLAS_CLIENT_SECRET,
ACCESS_TOKEN,
)

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

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': '[email protected]'}]
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, such as 10.0.0.1,tel:5402502334, or example.com. For links to be tracked properly, you must create the links before sending the draft.

What's next?