Hero Banner

How to manage contacts with Nylas Node SDK

8 min read

This blog post contains code for the Nylas API V2. Take a look at your latest docs to see Nylas API V3 Contacts Docs updated to work with Nylas API V3.

Intro

In this post, we are going to learn how to use the Nylas Node SDK to manage contacts. This will be useful to streamline working with contacts with minimal coding. We’ll first set up our environment, and then we’ll start accessing contacts using JavaScript. You can also find example code on the Nylas Samples code repository.

Prerequisites

Sign up here if you need to create a Nylas account for free! Follow the Quickstart to receive your account credentials. Ensure to save the access token to use below.

Environment

If you have used the Nylas Node SDK before, continue to the next section. If you need to configure your environment, take a look at the Environment setup from our code samples repository. Alternatively, you can check out this post on How to Send Emails with Nylas Node SDK to configure your environment.

Reading contacts

Let’s first code how to list our contacts. Let’s create listContacts.js:

// node-manage-contacts/listContacts.js

// Import your dependencies
import 'dotenv/config';
import Nylas from "nylas"

import Contact, { EmailAddress } from "nylas/lib/models/contact.js";
import EmailParticipant from 'nylas/lib/models/email-participant';

// Configure your Nylas client
Nylas.config({
    clientId: process.env.CLIENT_ID,
    clientSecret: process.env.CLIENT_SECRET,
});

const nylas = Nylas.with(process.env.ACCESS_TOKEN);
const nylasContacts = nylas.contacts;

/* Read from contacts */
try {
  const contacts = await nylasContacts.list({ limit: 5 });
  contacts.map(({ emailAddresses, id }) => console.log(`id: ${id} - email: ${emailAddresses[0].email}`));
} catch (err) {
  console.error("Read contacts error:\n", err);
}

The Nylas Node SDK wraps the Nylas API to retrieve a list of 5 contacts. Let’s try calling listContacts via the terminal:

$ node listContacts.js
id: <CONTACT_ID> - email: <EMAIL>
id: <CONTACT_ID> - email: <EMAIL>
id: <CONTACT_ID> - email: <EMAIL>
id: <CONTACT_ID> - email: <EMAIL>
id: <CONTACT_ID> - email: <EMAIL>

If everything worked, you will see the message in the terminal where five contacts will be listed with a <CONTACT_ID>, and <EMAIL>. We can use the CONTACT_ID to retrieve and update specific contacts, we’ll see this soon!

We can also paginate contacts using the offset property:

const contacts = await nylasContacts.list({limit: 2, offset: 3});

Now we’ve listed five contacts using the Nylas Node SDK.

Creating a contact

Let’s code how to create a new contact. Let’s create createContact.js:

// node-manage-contacts/createContact.js

// Import your dependencies
import 'dotenv/config';
import Nylas from "nylas"

import Contact, { EmailAddress } from "nylas/lib/models/contact.js";
import EmailParticipant from 'nylas/lib/models/email-participant';

// Configure your Nylas client
Nylas.config({
    clientId: process.env.CLIENT_ID,
    clientSecret: process.env.CLIENT_SECRET,
});

const nylas = Nylas.with(process.env.ACCESS_TOKEN);
const nylasContacts = nylas.contacts;

/* Create a contact */
try {
  const emailAddress = new EmailAddress({ type: 'work', email: '<EMAIL>'});

  const contact = new Contact.default(nylas, {
    givenName : 'Kevin',
    surname : 'Gill',
    birthday : '2005-09-09',
    jobTitle : 'Diner Buddies',
    notes : 'Great to grab breakfast with.',
    emailAddresses: [emailAddress],
  });

  // save the contact ID for updating the contact
  console.log('Contact created', response);
} catch(err) {
  console.error("Create contact error:\n", err);
}

Make sure you update the contact details and also the contact <EMAIL>. There are many configurations you can pass to create contacts, have a look at the Nylas API for more options. The API will also share more details on which fields are supported by each provider. For example the notes property is supported by Google and iCloud.

Let’s try running this script in the terminal:

$ node createContact.js
Contact created Contact {
  ...
  id: '<CONTACT_ID>',
  accountId: '<ACCOUNT_ID>',
  object: 'contact',
  givenName: 'Kevin',
  surname: 'Gill',
  birthday: '2005-09-09',
  jobTitle: 'Diner Buddies',
  notes: 'Great to grab breakfast with.',
  emailAddresses: [ EmailAddress { type: 'work', email: '<EMAIL>' } ],
  middleName: '',
  suffix: '',
  nickname: '',
  companyName: '',
  managerName: '',
  officeLocation: '',
  pictureUrl: '',
  imAddresses: [],
  physicalAddresses: [],
  phoneNumbers: [],
  webPages: [],
  groups: [],
  source: 'address_book',
  jobStatusId: '<JOB_STATUS_ID>'
}

If everything worked, you will see the message in the terminal where the create contact will be listed. Be sure to take node of the contact <CONTACT_ID> to use for updating the contact shortly.

Now we’ve created a contact using the Nylas Node SDK.

Updating a contact

Let’s try updating the contact previously created using the Nylas Node SDK. Let’s create updateContact.js:

// node-manage-contacts/updateContact.ts

// Import your dependencies
import 'dotenv/config';
import Nylas from "nylas"

import Contact, { EmailAddress } from "nylas/lib/models/contact.js";

// Configure your Nylas client
Nylas.config({
    clientId: process.env.CLIENT_ID,
    clientSecret: process.env.CLIENT_SECRET,
});

const nylas = Nylas.with(process.env.ACCESS_TOKEN);
const nylasContacts = nylas.contacts;

/* Update contact */
try {
  const contact = await nylasContacts.find('<CONTACT_ID>')

  contact.birthday = '2005-09-10';
  const response = await contact.save();

  //updated contact is returned in response
  console.log(response);
} catch (err) {
  console.error("Update contact error:\n", err);
}

Make sure to update the following variables:

  • CONTACT_ID to be the id of the contact that we created

Let’s try updating the contact via the terminal:

$ node updateContact.js
Contact created Contact {
  ...
  id: '<CONTACT_ID>',
  accountId: '<ACCOUNT_ID>',
  object: 'contact',
  givenName: 'Kevin',
  surname: 'Gill',
  birthday: '2005-09-10',
  jobTitle: 'Diner Buddies',
  notes: 'Great to grab breakfast with.',
  emailAddresses: [ EmailAddress { type: 'work', email: '<EMAIL>' } ],
  middleName: '',
  suffix: '',
  nickname: '',
  companyName: '',
  managerName: '',
  officeLocation: '',
  pictureUrl: '',
  imAddresses: [],
  physicalAddresses: [],
  phoneNumbers: [],
  webPages: [],
  groups: [],
  source: 'address_book',
  jobStatusId: '<JOB_STATUS_ID>'
}

If everything worked, you will see the message in the terminal where the contact will be listed with an updated birthday. If you try to update an auto-generated contact, you may see a message as follows:

Bad Request: <CONTACT_ID> is an auto-generated contact and this operation isnt supported for auto-generated contacts.

This means that contacts that we have not created cannot be modified. So only created contacts added can be modified.

Now we’ve updated one of our first contacts created using the Nylas Node SDK.

Deleted a contact

Let’s try removing the contact previously created using the Nylas Node SDK. Let’s create deleteContact.js:

// node-manage-contacts/deleteContact.ts

// Import your dependencies
import 'dotenv/config';
import Nylas from "nylas"

import Contact, { EmailAddress } from "nylas/lib/models/contact.js";

// Configure your Nylas client
Nylas.config({
    clientId: process.env.CLIENT_ID,
    clientSecret: process.env.CLIENT_SECRET,
});

const nylas = Nylas.with(process.env.ACCESS_TOKEN);
const nylasContacts = nylas.contacts;

/* Delete a Contact */
try {
  const response = await nylasContacts.delete('<CONTACT_ID>');

  // job_status_id is returned
  // { job_status_id: '<JOB_STATUS_ID>' }
  console.log(response);
} catch (err) {
  console.error("Delete contact error:\n", err);
}

Make sure to update the following variables:

  • CONTACT_ID to be the id of the contact that we created

Let’s try removing the contact via the terminal:

$ node deleteContact.js
{ response: { job_status_id: '<JOB_STATUS_ID>' } }

If everything worked, you will see the message in the terminal where the job_status_id will be listed and the contact will be removed from your contacts.

Now we’ve deleted our contact using the Nylas Node SDK.

Create contacts from emails

Let’s try creating multiple contacts from our last 3 emails. Let’s create createContactsFromEmails.js:

// node-manage-contacts/createContactsFromEmails.ts

// Import your dependencies
import 'dotenv/config';
import Nylas from "nylas"

import Contact, { EmailAddress } from "nylas/lib/models/contact.js";

// Configure your Nylas client
Nylas.config({
    clientId: process.env.CLIENT_ID,
    clientSecret: process.env.CLIENT_SECRET,
});

const nylas = Nylas.with(process.env.ACCESS_TOKEN);
const nylasContacts = nylas.contacts;
const nylasMessages = nylas.messages;

/* Create contacts from emails */
try {  
  const messages = await nylasMessages;
  const emails = await messages.list({ limit: 3 });

  emails.map(email => {
    email.from.map(async ({ name, email }) => {
      const firstName = name.split(' ').slice(0, -1).join(" ");
      const lastName = name.split(' ').slice(-1).join(" ");
  
      const emailAddress = new EmailAddress({ type: 'work', email});
  
      const contact = new Contact.default(nylas, {
        givenName: firstName,
        surname: lastName,
        emailAddresses: [emailAddress],
      });
  
      const response = await contact.save();
      console.log(response);
    })
  })  
} catch (err) {
  console.error("Create contacts from emails error:\n", err);
}

Let’s try running this script in the terminal:

$ node createContactsFromEmails.js
Contact {
  id: '<CONTACT_ID>',
  givenName: <GIVEN_NAME>,
  surname: <SURNAME>,
  emailAddresses: [ EmailAddress { type: 'work', email: <EMAIL> } ],
  jobStatusId: '<JOB_STATUS_ID>'
  ...
}
Contact {
  id: '<CONTACT_ID>',
  givenName: <GIVEN_NAME>,
  surname: <SURNAME>,
  emailAddresses: [
    EmailAddress { type: 'work', email: <EMAIL>com' }
  ],
  jobStatusId: '<JOB_STATUS_ID>'
  ...
}
Contact {
  id: '<CONTACT_ID>',
  givenName: <GIVEN_NAME>,
  surname: <SURNAME>,
  emailAddresses: [ EmailAddress { type: 'work', email: <EMAIL> } ],
  jobStatusId: '<JOB_STATUS_ID>'
  ...
}

If everything worked, you will see the message in the terminal where multiple contacts will be created based on your last three emails.

Now we’ve created multiple contact using the Nylas Node SDK.

Build Time!

You can find example code on the Nylas Samples code repository. Continue building with Nylas and learn more by visiting the Node SDK documentation.

Related resources

How to build a CRM in 3 sprints with Nylas

What is a CRM? CRM stands for Customer Relationship Management, and it’s basically a way…

How to create an appointment scheduler in your React app

Learn how to create an appointment scheduler in your React app using Nylas Scheduler. Streamline bookings and UX with step-by-step guidance.

Beyond APIs: Designing elegant, smart Web Components

Dive into the world of smart Web Components for advanced API integration solutions. Design elegant, customizable elements to elevate user experiences.