Send email messages in Nylas v2
Nylas offers multiple ways to send email messages. This page describes how to choose the best method for your Nylas application, how to create and send a draft email message, and how to send an email message without creating a draft.
Choose how to send email messages
Nylas offers two different ways to send email messages:
- Create and send a draft: This method is ideal for preparing email messages that don't need to be sent immediately. Drafts are synced to the provider's Draft folder, if possible.
- Send email message without creating draft: This method is ideal for sending a small number of email messages without saving them as drafts first. Email messages are synced to the provider's Sent folder, if possible.
In both cases, the sending operation is synchronous (meaning Nylas sends items one at a time) and the request blocks until the submission either succeeds or fails. If the submission fails, the Nylas Send API does not automatically try to send the email message again. For more information, see Deliverability for drafts and Send endpoint.
Create and send a draft
If you want to prepare an email message that doesn't need to be sent immediately, you can create a draft and send it later. When you create a draft with Nylas, it's synced with the provider. You can access it and make updates as long as it isn't deleted.
To create a draft in Nylas v2, make a POST /drafts
request.
curl --location --request POST 'https://api.nylas.com/drafts/' \
--header 'Authorization: Bearer <access_token>' \
--header 'Accept: application/json, application/gzip' \
--header 'Content-Type: application/json' \
--data-raw '{
"subject": "From Nylas",
"to": [{
"email": "swag@example.com",
"name": "Nylas"
}],
"from": [{
"email": "you@example.com",
"name": "Your Name"
}],
"reply_to": [{
"name": "Nylas",
"email": "swag@example.com"
}],
"reply_to_message_id": "1d00e908341a4a889ba4",
"body": "This email was sent using the Nylas email API. Visit https://nylas.com for details.",
"file_ids": [ "0a512d9b79584e989ca7" ]
}'
🔍 All parameters for a Create Draft request are optional. If you make the request with no parameters, Nylas creates a draft with no content.
The following parameters are useful to keep in mind as you create your request:
reply_to
: Includes names and email addresses that Nylas uses to set a Reply-to address in the message's Reply-to header.- A Reply-to address is where replies to the email message are sent. This doesn't have to be the same as the From address.
- Not all providers support setting a Reply-to address in drafts.
reply_to_message_id
: The ID of the email message that you're replying to.file_ids
: Includes IDs of files that you attached to the draft.- You must upload the files before you can attach them to a draft.
You can also create a draft using the Nylas SDKs, as in the following examples.
require 'nylas'
nylas = Nylas::API.new(APP_ID, APP_SECRET, ACCESS_TOKEN)
file = nylas.files.create(file: File.open(File.expand_path('RubyLogo.png'), 'r')).to_h
draft = nylas.drafts.create(to: [{ email: 'swag@example.com', name: 'Nylas' }],
cc: [{ email: 'dorothy@example.com',
name: 'Dorothy Vaughan' }],
bcc: [{ email: 'Lamarr@example.com',
name: 'Hedy Lamarr' }],
subject: 'From Nylas',
body: 'This email was sent using the ' +
'Nylas Email API. ' +
'Visit https://nylas.com for details.',
file_ids: [file[:id]])
puts "Draft Id: #{draft.id} | Draft Version: #{draft.version}"
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;
import com.nylas.*;
public class CreateDraft {
public static void main(String[] args) throws RequestFailedException, IOException {
NylasClient client = new NylasClient();
NylasAccount account = client.account("<ACCESS_TOKEN>");
Files files = account.files();
byte[] myFile = java.nio.file.Files.readAllBytes(
Paths.get("src/main/java/JavaLogo.png"));
File upload = files.upload("JavaLogo.png", "image/png", myFile);
Draft draft = new Draft();
draft.setTo(List.of(new NameEmail("Nylas", "swag@example.com")));
draft.setCc(List.of(new NameEmail("Dorothy Vaughan","dorothy@example.com")));
draft.setBcc(List.of(new NameEmail("Hedy Lamarr","Lamarr@example.com")));
draft.setSubject("With Love, from Nylas");
draft.setBody("This email was sent using the Nylas Java email API. Visit https://nylas.com for details.");
draft.attach(upload);
draft = account.drafts().create(draft);
System.out.println("Draft " + draft.getSubject() + " was created with ID " + draft.getId());
}
}
When you're ready, you can send the draft by making a POST /send
request or using the Nylas SDKs. You must specify the draft_id
for both methods, and the version
for the API call.
⚠️ Your request will fail if Nylas finds a version of the draft on the provider that is newer than the one you're trying to send. To get the latest version
, make a GET /draft/{draft_id}
request.
curl -X POST 'https://api.nylas.com/send' \
-H 'Authorization: Bearer <access_token>' \
-d '{
"draft_id": "{draft_id}",
"version": 0
}'
require 'nylas'
nylas = Nylas::API.new(APP_ID, APP_SECRET, ACCESS_TOKEN)
draft = nylas.drafts.find("{draft_id}")
draft.send!
import java.io.IOException;
import com.nylas.*;
public class SendDraft {
public static void main(String[] args) throws RequestFailedException, IOException {
NylasClient client = new NylasClient();
NylasAccount account = client.account("<ACCESS_TOKEN>");
Draft draft = account.drafts().get("<DRAFT_ID>");
account.drafts().send(draft);
}
}
Create and send an email message
If you want to create and send an email message immediately, you can do so without creating a draft.
To create and send an email message in Nylas v2, make a POST /send
request or use the Nylas SDKs.
curl --location --request POST 'https://api.nylas.com/send' \
--header 'Authorization: Bearer <access_token>' \
--header 'Accept: application/json, application/gzip' \
--header 'Content-Type: application/json' \
--data-raw '{
"subject": "From Nylas",
"to": [{
"email": "swag@example.com",
"name": "Nylas"
}],
"from": [{
"email": "you@example.com",
"name": "Your Name"
}],
"reply_to": [{
"name": "Nylas",
"email": "swag@example.com"
}],
"reply_to_message_id": "1d00e908341a4a889ba4",
"body": "This email was sent using the Nylas email API. Visit https://nylas.com for details.",
"file_ids": [ "0a512d9b79584e989ca7" ]
}'
require 'nylas'
nylas = Nylas::API.new(APP_ID, APP_SECRET, ACESS_TOKEN)
file = nylas.files.create(file: File.open(File.expand_path('RubyLogo.png'), 'r')).to_h
nylas.send!(
to: [{ email: 'swag@example.com', name: 'Nylas' }],
cc: [{ email: 'dorothy@example.com',
name: 'Dorothy Vaughan' }],
bcc: [{ email: 'Lamarr@example.com',
name: 'Hedy Lamarr' }],
subject: 'From Nylas',
body: 'This email was sent using the ' +
'Nylas email API. ' +
'Visit https://nylas.com for details.',
file_ids: [file[:id]]
).to_h
import java.lang.Exception;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.List;
import com.nylas.*;
public class SendEmail {
public static void main(String[] args) throws RequestFailedException, IOException {
NylasClient client = new NylasClient();
NylasAccount account = client.account("<ACCESS_TOKEN>");
Files files = account.files();
byte[] myFile = java.nio.file.Files.readAllBytes(
Paths.get("src/main/java/JavaLogo.png"));
File upload = files.upload("JavaLogo.png", "image/png", myFile);
Draft draft = new Draft();
draft.setSubject("With Love, from Nylas");
draft.setBody("This email was sent using the <b>Java SDK</b> for the Nylas Email API. Visit <a href='https://nylas.com'>Nylas.com</a> for details.");
draft.setTo(List.of(new NameEmail("Nylas", "swag@example.com")));
draft.attach(upload);
account.drafts().send(draft);
}
}
Draft deliverability and the Send endpoint
Send operations are synchronous (meaning Nylas sends items one at a time), and the request blocks until the submission succeeds or fails. If the request fails, the Nylas Send API does not automatically try to send the email message again.
💡 A successful request to the Send endpoint can sometimes take up to two minutes for self-hosted Exchange accounts, though the average send time is approximately two seconds. To ensure that you receive a response from Nylas, set the maximum timeout to 150 seconds.
Nylas recommends that you apply a backoff strategy when the Send API returns HTTP 503
errors. Your application might need to wait between 10–20 minutes, or else SMTP servers might continue to refuse connections for the affected end user.
For information on the number of email messages you can send per day, see the Provider rate limits documentation. If large-volume sending continues to fail for your application, Nylas recommends you switch to a transactional sending service (for example, Mailgun, Sendgrid, Mandrill, or Amazon SES).
Sending errors
Sometimes, delivery of email messages might fail if the end user's email gateway rejects the message. This can happen for a number of reasons, including illegal attachment data, bad credentials, or rate-limiting.
If the email message is submitted successfully, the server responds with a 200 OK
HTTP response. If the message is not submitted, the server responds with an error code.
Status Code | Type | Description |
---|---|---|
200 |
OK | Your email message has been successfully submitted for sending. |
400 |
Bad request | Your request was not formed properly, or contains an invalid parameter. The most common cause is invalid JSON. |
402 |
Message rejected | The provider rejected the email message because of its content or recipients. If the error includes "Sending to at least one recipient failed", it means that your email message might have been delivered to only a subset of recipients. |
403 |
Unauthorized | The server was not able to authenticate with the provider. Re-authenticate the end user and try again. |
422 |
Mail provider error | An error occurred while the provider was sending the email message. See the server_error parameter in the response JSON for more information. |
429 |
Quota exceeded | The end user has exceeded their provider's sending quota. There is no reliable way to determine these limits. Wait and try again later. |
429 |
Account throttled | The account is in a throttled state and the mail server has asked Nylas to temporarily stop making requests. Wait and try again later. |
429 |
Nylas API rate limit | You made too many requests to the Nylas API too quickly. Wait and try again later. For more information, see the Rate limiting documentation. |
503 |
Service unavailable | Nylas encountered an error while connected to the provider. Wait and try again. |
⚠️ If any participant email addresses contain non-ASCII characters (for example, characters with accents or other diacritics), email message delivery fails and Nylas returns a 402
error with the "Sending to at least one recipient failed" message. Currently, Nylas cannot send email messages to email addresses that contain these special characters.
The response body also contains a JSON object with information about the specific error, including the attributes in the following table.
Parameter | Type | Description |
---|---|---|
type |
string | The type of error encountered. |
message |
string | A brief, human-readable description of the error. |
server_error |
string | (Optional) The original error returned by the end user's email server. |
The email message ID header
Sending an email using the Nylas Email API creates a unique message_id_header
in the sender's database, similar to the example below.
4ottpfaje0kqx8iagoih0h3tp-0@mailer.nylas.com
This value is required for the provider's SMTP server, and is part of the standard protocol when using Nylas as an email client. The header is visible only on the sender's database, and is not an email object that you can use or update.
The provider's SMTP server might modify this value during the sending process. Nylas recommends you avoid using this message_id_header
with the @mailer.nylas.com
domain for email configuration.
Override sender display name
When you send email messages using Nylas, you can set the sender's display name by modifying the from.name
parameter in your request, as in the following example.
⚠️ Some Exchange servers might ignore From headers when sending email messages, and instead default to the sender's display name. When this happens, Nylas cannot change the sender's display name. Instead, the end user must change it in their account settings.
curl --request POST \
--url https://api.nylas.com/send \
--header 'Accept: application/json, application/gzip' \
--header 'Authorization: Bearer <ACCESS_TOKEN>' \
--header 'Content-Type: application/json' \
--data '{
"subject": "From Nylas",
"to": [{
"name": "John Doe",
"email": "john.doe@example.com"
}],
"from": [{
"name": "Nyla",
"email": "nyla@example.com"
}],
"reply_to": [{
"name": "John Doe",
"email": "john.doe@example.com"
}],
"body": "This email was sent using the Nylas Email API. Visit https://nylas.com for details."
}'
If you don't include the from
field when you send an email message, Nylas uses the account's default display name. You can find an account's display name by making a GET /account
request.
What's next?
- Learn more about email message tracking.
- Read Nylas' blog post: Send and Read Emails Using Node-Red and the Nylas APIs.
- Read Nylas' blog post: How to Send an Email in Any Language Using the Nylas APIs.
Video walkthroughs
Prefer video? You can watch Nylas' livestream, Coding with Nylas.