Turn Your App Into a Scheduling Powerhouse With Nylas

Learn how the Nylas Email, Calendar, and Contacts APIs enable developers to turn their app into a scheduling powerhouse.

Turn Your App Into a Scheduling Powerhouse With Nylas

The events on your user’s weekly calendar don’t exist in a vacuum; they’re the result of relationships he has cultivated across numerous communications channels. Most people regularly engage in email communications that span across numerous aspects of their life, but one area that email is  particularly important is when your application’s users are building relationships with clients at other companies and organizations.

When your user’s day is packed with meetings, he might want to quickly review the details of his next meeting to make sure he’s fully prepare to impress his client. In addition, he might need to make adjustments to the meeting based on emails he’s shared with the client over the past couple of days, such as inviting new participants, changing the time of the meeting, or adding items to the itinerary.

There is a strong relationship between the events on your user’s calendar, the contacts in his contacts book, and the recent email communications he’s been involved in. This post will explore ways that you can improve your application by adding more context and insight to upcoming events on a user’s calendar with the Nylas Platform.

Empower Your Users With Better Context

The Nylas Platform provides simple REST APIs for email, calendar, and contacts and makes it easy to integrate 100% of all email, calendar, and contacts providers into your app. Nylas enables you to quickly build your email, calendar, and contacts functionality so you can focus on the features your users love.

This blog will show you how to add the following value to your app:

You’ll learn how to use Nylas as the foundation for features your users will love. Ready to turn your app into a schedule management powerhouse? Let’s take a look at how to build functionality like this:

Build user interfaces that let your users better manage their schedule

How to Use Nylas to Build Your Email, Calendar & Contacts Integration

Now, we’ll take a look at what it takes to use the Nylas Email, Calendar, and Contacts APIs to add new functionality to your app. For this example, we’ll use the Nylas Python SDK, but we also offer SDKs for JavaScript (Node.js), Java, and Ruby.

Before starting, you’ll need to take 30 seconds to register your Nylas account and get your developer API keys. Specifically, you need the Client ID and Client Secret for your Nylas app, and an access token for an email account that you want to use. We’ll save these as environment variables so they’re more secure; take a look at our guide on Python environment variables to learn more.

You also need to install the nylas package by heading over to the terminal and running the command pip install nylas. Now we’re ready to start writing code!

Initialize the Nylas Client

To start, import the os and datetime packages; os lets us access our system’s environment variables and datetime will make it easier to access events within specific timeframes. We also need to import theAPIClient object from nylas which allows us to make requests to the Nylas Platform.

import os
import datetime
from nylas import APIClient

CLIENT_ID = os.environ['CLIENT_ID']
CLIENT_SECRET = os.environ['CLIENT_SECRET']
ACCESS_TOKEN = os.environ['ACCESS_TOKEN']

nylas = APIClient(
    CLIENT_ID,
    CLIENT_SECRET,
    ACCESS_TOKEN,
)

Find The User’s Meetings For The Current Week

In our example, our user keeps all of their meetings with external clients on a calendar named “Client Meetings.” We want to let them quickly review all of the meetings they have coming up this week so they can prepare for all of them. Fortunately, the Nylas Calendar API provides all of the tools we need to accomplish this.

We’re going to show learn how to to do the following:

  1. Get all Calendars Available via /calendars endpoint
  2. Select the calendar_id for the calendar named “Client Meetings”
  3. Create a unix timestamp for the start of day Monday and end of day Friday
  4. Query for all events that fall in that time range in that specific calendar via the /events endpoint
calendars = nylas.calendars.all()
# Get the calendar_id of the "Client Meetings" calendar
calendar_id = [ calendar['id'] for calendar in calendars if 'Client Meetings' in calendar['name'] ][0]

today = datetime.date.today()
# Get Monday's datetime and convert it to a unix timestamp
monday = today + datetime.timedelta(days=-today.weekday())
monday_unix = monday.strftime("%s")

# Get Friday's datetime
friday = monday + datetime.timedelta(days=5)
friday_unix = friday.strftime("%s")

# Return all events between Monday and Friday of this week
events = nylas.events.where(calendar_id=calendar_id, starts_after=monday_unix, ends_before=friday_unix)

Now we’ll use /events/{id} to return the title, list of participants, description, and start and end times for each of this week’s events.

for event in events:
    print("Title: {} | Participants: {} | Description: {} | Start Time: {} | End Time: {}".format(
        event.title,
        ",".join([participant['email'] for participant in event.participants]),
        event.description,
        event.when['start_time'],
        event.when['end_time']
        ))

Here’s an example of the data that this code example would return.

Title: Discuss the Latest Line of Nuclear Ornithopters | Participants: marie@radioactivity.com , leo@ornitech.com | Description: The Latest model of our Nuclear Ornithopters is out! Let's talk about why you might want to upgrade. | Start Time: 1585792800 | End Time: 1585796400

Find Details About Event Participants

The Nylas Contacts API enables you to pull in rich contact data from a user’s account so you can add more context to the events and emails they share with their contacts. Now, we’ll take a look at one of the events our user has coming up this week and pull in additional information about the participants that can better inform our user about their upcoming meeting. Nylas enables you to find important information including job title, company, phone number, location, and more.

# Select the first event and get the list of participants
first_event = events[0]
participants = first_event['participants']

# Use the Nylas Contacts API to return detailed information about each participant
for participant in participants:
    contacts = nylas.contacts.where(email=participant['email'])
    if contacts.all():
        contact = contacts[0]
        phone_number = next(iter(list(contact['phone_numbers'].values())), None)
        email = next(iter(list(contact['emails'].values())), None)
        print("Full Name: {} | Email: {} | Phone Number: {} | Location: {} | Profile Picture: {} | Company Name: {} | Job: {}".format(
            contact['given_name'] + " " + contact['surname'],
            email,
            phone_number,
            contact['office_location'],
            contact['picture_url'],
            contact['company_name'],
            contact['job_title'],
            ))

Here’s an example of the data that Nylas returns.

Full Name: Marie Curie | Email: ['marie@radioactivity.com'] | Phone Number: ['(040) 719-3466'] | Location: Warsaw, Poland | Profile Picture: https://api.nylas.com/contacts/marie/picture | Company Name: Radioactivity Inc. | Job: Physicist
Full Name: Leonardo Da Vinci | Email: ['marie@radioactivity.com'] | Phone Number: ['(020) 515-1967'] | Location: Vinci, Italy | Profile Picture: https://api.nylas.com/contacts/leo/picture | Company Name: Ornitech Unlimited | Job: Flight Architect

Add Context With Email Data

Now it’s time to use the Nylas Email API to provide our user with information about the recent emails they’ve shared with the participants in the upcoming meeting. We want to show our user all emails they’ve received from the event participants in the last 2 weeks so they can take any actions that might be required or review emails and their attachments to be better informed about the upcoming meeting.

To do so, we’ll use /threads to find all related email threads, and /messages to return information from each specific email that was sent as part of the thread.

threads = []
for participant in participants:
    two_weeks_ago = datetime.date.today() - datetime.timedelta(14)
    unix_two_weeks_ago = two_weeks_ago.strftime("%s")
    # Search across the user's email inbox for threads in last 14 days that are from any of the event participants.
    threads = nylas.threads.where(from_=participant['email'], last_message_after=unix_two_weeks_ago)

# For all matching threads, return the subject line, snippet, and date for all messages from that thread
for thread in threads:
    for message_id in thread['message_ids']:
        message = nylas.messages.get(message_id)
        print("Subject Line:\n {} \n Snippet: \n {} \n Date: \n {}".format(
            message.subject,
            message.snippet,
            message.date
            ))

Here’s an example of what this might look like.

Subject Line:
 Re: Meeting on Thursday
 Snippet:
 I've got a conflict and may need to reschedule.
 Date:
 1585346511
Subject Line:
 Nuclear Ornithopters
 Snippet:
 Hey Al, I'm wondering if you might know anything about some of the Nuclear Ornithopters that are hitting the market.
 Date:
 1585346511

Some of these emails include attachments that might be important to review before the meeting, so here is how you can access them using the /files endpoint.

for thread in threads:
    for message_id in thread['message_ids']:
        message = nylas.messages.get(message_id)    
        if message.files:
            for file_ in message.files:
                file_object = nylas.files.get(file_['id'])
                print("File: {} | Content Type: {}".format(
                    file_object.filename,
                    file_object.content_type
                    ))
                open(file_object.filename, 'wb').write(file_object.download())

One last ability we want our user to have is to identify people who were included in the recent email communications, but might have missed the invite to our upcoming meeting. We wouldn’t want to leave them out, so our next example will check the recent emails with the meeting participants, identify anyone who hasn’t been invited to the meeting, add them as a participant, and send an email notification to everyone.

current_participants = [ participant['email'] for participant in participants ]
new_participants = []

# For all matching threads, return the participants who aren't also a participant in the event
for thread in threads:
    for thread_participant in thread.participants:
        if thread_participant['email'] not in current_participants + new_participants :
            new_participants.append(thread_participant['email'])


print("Adding the following participants to the event:")
for participant in new_participants:
    print(participant)

# Modify the upcoming event to add the missing participants
for participant in new_participants:
    first_event.participants.append({'email' : participant})
    first_event.save(notify_participants='true')

Here’s what our script will log to the console:

Adding the following participants to the event:
albert.e@particletech.com

That’s everything you need to know to get started building your next email, calendar, and contacts integration. Want all of this example code in one place? Head over to the Nylas docs.

Build More Features Users Will Love With Nylas

The Nylas Platform is the easiest way to integrate with 100% of calendar providers in the world. Here are a few resources to teach you about what else is possible with Nylas.

You May Also Like

How to create and read Webhooks with PHP, Koyeb and Bruno
How to create a scheduler with Python and Taipy
How to create and read Google Webhooks using Kotlin

Subscribe for our updates

Please enter your email address and receive the latest updates.