Reviving Friendships with the Nylas Email and Contacts API | Nylas

Reviving Friendships with the Nylas Email and Contacts API

Use Nylas’ Email and Contacts API to make Contact Roulette, a fun app to reconnect with friends.

Jieun Kim | November 25, 2019

As a developer, you know that playing with code is a great way to get your creative juices going – in fact, it often helps you develop ideas for applications you want to further build out.  But whether it turns out to be the Next Big Thing or not, making a lightweight app using Nylas’s contact and email API is an effective and fun way to explore the Nylas API. 

Our friend Anthony, whom we met at Scale17x,  wanted to quickly build a feature to re-connect with contacts in his contacts book.

Using a few endpoints from the Nylas API and the GIPHY API, Anthony created an amusing client-side application called ‘Contact Roulette’ that sends a friendly gif to a randomly selected contact in your inbox. He was inspired to create it when thinking of a way to reconnect with friends and acquaintances he hadn’t had the time to get in touch with recently. What a way to re-establish contact!

Let’s take a look at how he did it:

First, he set up an Nylas account and application so that he’d be ready to authenticate an account right away. 

Then, he wrote a little HTML and hooked up a ‘Get Started’ button to call Nylas’ /oauth/authorize endpoint. This way, when a user lands on his page and clicks the button, the user’s email account authenticates, an access token is generated and can be used to call the email and contact API endpoints.

<div id="get-started" class="content-box">

        <h2>Contact Roulette</h2>

        <p>Haven't talked to your friends lately?</p>

        <p>Send a gif randomly to one of your contacts with Nylas!</p>

        <center>

          <iframe src="https://giphy.com/embed/14aUO0Mf7dWDXW" width="280" height="280" frameBorder="0" class="giphy-embed" allowFullScreen></iframe>

          <br />

          <a class="btn btn-large btn-primary" href="https://api.nylas.com/oauth/authorize?client_id={client_id_here}&response_type=token&scopes=email,contacts&redirect_uri=https://anthonykosednar.com/contact-roulette/">Get Started</a>

        </center>

      </div>

*Note – things move fast at Nylas, and since the time Anthony made this app, Nylas’ code has been updated to to keep your data more secure. For example, instead of general scopes that allow access to large swaths of data, we now have granular scopes that access only exactly the data needed. So, if today, you were looking to do something similar, your URL would look something like this:

https://api.nylas.com/oauth/authorize?login_hint=EMAIL_ADDRESS&client_id=NYLAS_CLIENT_ID&response_type=token&redirect_uri=MY_REDIRECT_URI&scopes=email.send,email.read_only&state=CSRF_TOKEN

Anthony then checks the page URL for the access token and stores it. Now a call can be made to the /contacts endpoint and a bit of code ensures a random contact is selected and stored in the ‘contact_email’ variable:

access_token = url.searchParams.get('access_token');

          $.ajax({     

            type: "GET",

            url: 'https://api.nylas.com/contacts',

            headers: { 'authorization': access_token },

            async: false }).done(function( data ) {

              if (isNaN(data)) {

                num_contacts = data.length

                // Make sure we get a contact (but not a no-reply contact)

                contact_email = ""

                while (contact_email == "" || contact_email.includes("no-reply") || contact_email.includes("noreply")) {

                  random_contact = Math.floor(Math.random() * (num_contacts-1)) + 0;

                  console.log("Random Contact "+random_contact.toString());

                  if ('emails' in data[random_contact]){

                    if (data[random_contact]["emails"].length > 0) {

                      if('email' in data[random_contact]["emails"][0]){

                        contact_email = data[random_contact]["emails"][0]["email"];

                      }

                    }

                  }

                }

                console.log("Contact Email - "+contact_email);

              }

              else  {

                // Errorz!

                console.log("Contact error");

                $("#waiting").hide();

                $("#error").show();

              }

            return true;

          });

Next, Anthony makes a call to the /account endpoint which returns information about the user’s account, including the user’s email, which will be used later in the payload of sending the email. 

          $.ajax({     

            type: "GET",

            url: 'https://api.nylas.com/account',

            headers: { 'authorization': access_token },

            async: false }).done(function( data ) {

              if (isNaN(data)) {

                to_email = data["email_address"];

                to_name = data["name"];

              }

              else  {

                // Errorz!

                console.log("Contact error");

                $("#waiting").hide();

                $("#error").show();

              }

            return true;

          });

What now? We can’t forget about the GIF, of course! 

jerry, elaine and george are excited to see each other

Here’s where Anthony makes a call to the Giphy API  to grab a GIF URL to send to the random contact:

 gif_url = ""

          $.ajax({     

            type: "GET",

            url: 'https://api.giphy.com/v1/gifs/random?api_key='+API_KEY,

            async: false }).done(function( data ) {

              if (isNaN(data)) {

                gif_url = data["data"]["images"]["downsized"]["url"];

                console.log("GIF URL - "+gif_url);

              }

              else  {

                // Errorz!

                console.log("GIF error");

                $("#waiting").hide();

                $("#error").show();

              }

            return true;

          });

As you saw above, Anthony stores the sender’s email in a variable he calls ‘to_email’; the random contact’s email in a variable he calls ‘contact_email’, and the GIF URL in the ‘gif_url’ variable –  having assembled the data to properly format the payload, Anthony makes a call to the /send endpoint. 

  if(gif_url != ""){

            var data = JSON.stringify({

              "to": [

                {

                  "name": contact_email,

                  "email": contact_email

                }

              ],

              "subject": "Hey - Check out this GIF!",

              "from": [

                {

                  "name": to_name,

                  "email": to_email

                }

              ],

              "body": "<center><p style='font-size:14px;font-style:bold;'><b>Hey!<br /><br />Here's a random GIF for your day.</b></p><br /><img src='"+gif_url+"' /><br /><br /><b>Powered By:</b><br /><br /><a href='https://nylas.com'><img src='https://theme.zdassets.com/theme_assets/786754/3de63879d1497f06db3e3c957970a10a7a9c6465.png' width='100px' /></a></center>"

            });

            var xhr = new XMLHttpRequest();

            xhr.withCredentials = true;

            xhr.addEventListener("readystatechange", function () {

              if (this.readyState === this.DONE) {              

                $("#waiting").hide();

                $("#done").show();

              }

            });

            xhr.open("POST", "https://api.nylas.com/send");

            xhr.setRequestHeader("authorization", "JifiixmjBJW9arJb2TpdUlodJ7GJe4");

            xhr.send(data);

          }

        }

        else{

          // Show the right sections

          $("#get-started").show();

          $("#waiting").hide();

          $("#done").hide();

          $("#error").hide();

        }

      });

And voila! Bonhomie ensues— 

So, remember, the next time you feel daunted about getting started with the  Nylas API, try your hand at making something small and fun by focusing on one idea like ‘Contact Roulette’ and get a feel for how the Nylas API can help you build what you want (featuring GIFs or otherwise). And if you need a little inspiration to get going, you can always check out our quickstart guides.

About the Author

jieun kim is a technical writer based in nyc. in her spare time, she enjoys contemplating unusual shapes and accumulating large stacks of books.

Ready to Start Building?

Connect up to 10 accounts for free today. No credit card required.