Build Complete Email Draft & Send Functionality with Nylas

Build Complete Email Draft & Send Functionality with Nylas

6 min read
Tags:

If you want to add email functionality to your app, the ability to send an email is something your users probably expect. Investigating the various options for connecting to email service providers can be a daunting task that requires you to read through complex provider documentation and implement niche protocols like SMTP and IMAP. Why spend your time becoming an expert in email integrations when it could be better spent building the features your users love? 

The Nylas Platform provides a single point of integration that instantly connects 100% of email, calendar and contacts providers to your app, via simple REST APIs. With Nylas, you can add email functionality to your app in minutes; this article will show you how build complete email draft and send functionality with the Nylas Email API.

Getting Started with Inbox Zero

Inbox Zero is a demo inbox application that you can use to explore and understand the Nylas API. It’s built using:

  • Next.js, a framework for making server-rendered React apps
  • Express.js to create RESTful endpoints on the server
  • JSON Web Tokens (JWT) for authentication
  • Lowdb, a lightweight key-value database powered by Lodash, for storing user information
The Inbox Zero Homepage

Drafting & Sending Emails

Inbox Zero is all about getting a grip on your incoming mail so we’ll focus on creating reply emails, but the same principles apply for new outgoing threads. Here’s the steps:

  1. Create a draft and set up the metadata for a reply email. 
  2. Set up infrastructure to upload attachments
  3. Put it all together and send an email!
Let’s get started!

Draft an Email

Inbox Zero includes a reply button that opens up a view to let the user draft an email. When the use hits this button, there are some states that need to be setup for the view initialization. The first step is to figure out who the email will be sent to. A reply should be sent to the previous sender, but it should also include anyone else who is on the to, cc, and bcc lines. Lastly, we don’t want to send the reply to the user themselves, so their email address is filtered out.

const lastSentMessage = thread.messages[0];
const participantsToEmails = participants =>
        participants
                .map(p => p.email)
                .filter(email => email !== account.emailAddress)
                .join(",");

Next, the script defines an outgoing object that will be used to keep track of the eventual payload that will be sent to the message reply route.

const outgoing = {
        to: participantsToEmails([
                ...lastSentMessage.to,
                ...lastSentMessage.from
        ]),
        cc: participantsToEmails(lastSentMessage.cc),
        bcc: participantsToEmails(lastSentMessage.bcc)
}

Once the recipient state is set up, it’s time to present the user with an email editor to let them write their message, and update the recipients as needed; Inbox Zero uses Quill for easy, rich text editing. On the back end, the content of the message is placed into the body property of the outgoing message object.

Add Attachments

No email draft functionality is complete without the ability to add attachments. The first step to add an attachment is  to upload the file to the Nylas Platform. To do so, we need an HTML form that the user can interact with to select a file that will be provided to the attachment upload route. Inbox Zero uses the Formidable module for interpreting the file upload data and Node’s built-in fs module for lifting the file from disk.

const formidable = require("formidable");
const { promises: fs } = require("fs");

const form = formidable({ multiples: true });
form.parse(req, async (error, fields, files) => {
        const upload = files.upload;
        
        const filename = upload.name;
        const data = await fs.readFile(upload.path);
        const contentType = upload.type;

Once the file has been selected by the user, the extracted file data is sent to the Nylas Files endpoint

const file = nylas.files.build({
        filename,
        data,
        contentType
});
await file.upload();

After upload, the file object is updated with the Nylas ID for the uploaded file because this is needed to attach the file to the email draft.

res.json({
        id: file.id,
        filename: file.filename
});

Finally, the file is attached to the email by appending the file ID and name to the files array in the outgoing message object.

const  file = await response.json(); // Response from file upload route
outgoing.files = [...outgoing.files, file];

Send an Email

When the user hits the send button they trigger the reply route with the thread ID in the URL and the outgoing message information in the request body. The first thing this route does is mark the original email thread as read since the user has now addressed it.

const id = req.params.id;
const thread = await nylas.threads.find(id);
thread.unread = false;

Then, it creates a new draft object. 

const draft = nylas.drafts.build();

Next, the thread metadata is used to set the subject line and to set the replyToMessageId to be the ID of the last message in the thread. Setting the replyToMessageId properly is important because it helps mail providers associate messages with threads so that they show up properly for the recipients.

draft.subject = thread.subject;
draft.replyToMessageId = thread.messageIds[thread.messageIds.length - 1];

Then, the app fills in the message contents and include the IDs of any attachments. 

draft.to = req.body.to;
draft.cc = req.body.cc;
draft.bcc = req.body.bcc;
draft.body = req.body.body;
draft.files = req.body.files;

The very last step is to send the email.

await draft.send();
await thread.save();

Extend Your Email Functionality With Nylas

This article outlines what it takes to build full email draft and send functionality, but why stop there? The Nylas Email API also allows you to instantly connect 100% of email accounts to your app in minutes and enables you to also build threaded email inbox views. With Nylas, developers also unlock the full capability of users’ calendars and contact books too, and these combined with email functionality allow you to turn your app into a scheduling powerhouse. With Nylas, you can build deeply contextual experiences that let your users access their email, calendar, and contacts seamlessly from within your app. Get started today!

Related resources

Intelligent Workflow Automations Coming to the Nylas Platform

Platform updates help developers quickly and securely build new productivity features for their end-users.

Nylas Beats Kloudless on Security, Performance, Feature Depth & Pricing

Kloudless doesn’t accurately portray the capabilities of their product, so why would you trust them for your next integration?

Reduce Deployment Time by 30% With Continuous Delivery and GitHub Actions

Learn how Nylas improved our continuous delivery pipeline by migrating from Jenkins to GitHub Actions.