Mail service for the Sendgrid API
This is a dedicated service for interaction with the mail endpoint of the Sendgrid API.
Installation
Install with npm
or yarn
:
npm install @sendgrid/mail
yarn add @sendgrid/mail
Basic usage
Initialization with API key
Load the library and set the API key if you haven’t set it before:
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
Single email to one recipient
Load the library, prepare your email data and use the send
method:
const sgMail = require('@sendgrid/mail');
const data = {
to: 'recipient@example.org',
from: 'sender@example.org',
subject: 'Hello world',
text: 'Hello plain world!',
html: '<p>Hello HTML world!</p>',
};
sgMail.send(data);
Single email to multiple recipients
The to
field can contain an array of recipients, which will send a single email with all of the recipients in the to
field. The recipients will be able to see each other:
const sgMail = require('@sendgrid/mail');
const data = {
to: ['recipient1@example.org', 'recipient2@example.org'],
from: 'sender@example.org',
subject: 'Hello world',
text: 'Hello plain world!',
html: '<p>Hello HTML world!</p>',
};
sgMail.send(data);
Multiple emails to multiple recipients
If you want to send multiple individual emails to multiple recipient where they don't see each others email addresses, use sendMultiple
instead:
const sgMail = require('@sendgrid/mail');
const data = {
to: ['recipient1@example.org', 'recipient2@example.org'],
from: 'sender@example.org',
subject: 'Hello world',
text: 'Hello plain world!',
html: '<p>Hello HTML world!</p>',
};
sgMail.sendMultiple(data);
Note that sendMultiple(data)
is a convenience shortcut for send(data, true)
, and alternatively you can also set the isMultiple
flag to true
on your data
object.
Multiple single emails
The send
method also accepts an array of email data if you want to send multiple different single emails with for example different content and sender values. This will send multiple requests (in parallel), so be aware of any API rate restrictions:
const sgMail = require('@sendgrid/mail');
const emails = [
{
to: 'recipient1@example.org',
from: 'sender@example.org',
subject: 'Hello recipient 1',
text: 'Hello plain world!',
html: '<p>Hello HTML world!</p>',
},
{
to: 'recipient2@example.org',
from: 'other-sender@example.org',
subject: 'Hello recipient 2',
text: 'Hello other plain world!',
html: '<p>Hello other HTML world!</p>',
},
];
sgMail.send(emails);
CC, BCC and Reply To
You can specify the cc
, bcc
and replyTo
fields for more control over who you send the email to and where people will reply to:
const data = {
to: 'recipient@example.org',
cc: 'someone@example.org',
bcc: ['me@example.org', 'you@example.org'],
from: 'sender@example.org',
replyTo: 'othersender@example.org',
subject: 'Hello world',
text: 'Hello plain world!',
html: '<p>Hello HTML world!</p>',
};
Flexible email address fields
The email address fields (to
, from
, cc
, bcc
, replyTo
) are flexible and can be any of the following:
const data = {
to: 'someone@example.org',
to: 'Some One <someone@example.org>',
to: {
name: 'Some One',
email: 'someone@example.org',
},
to: [
'someone@example.org',
'Some One <someone@example.org>',
{
name: 'Some One',
email: 'someone@example.org',
},
],
};
Handling success/failure
The send
and sendMultiple
methods return a Promise
, so you can handle success and capture errors:
sgMail
.send(data)
.then(() => {
})
.catch(error => {
console.error(error.toString());
const {message, code, response} = error;
const {headers, body} = response;
});
Alternatively, pass a callback function as the last parameter:
sgMail
.send(data, (error, result) => {
if (error) {
}
else {
}
});
Advanced usage
All other advanced settings are supported and can be passed in through the data object according to the expected format as per the API v3 documentation. Note that you can use either camelCase
or snake_case
for property names.
Using transactional templates
Configure the substitution tag wrappers globally:
sgMail.setSubstitutionWrappers('{{', '}}');
Then provide a template ID and substitutions:
const data = {
templateId: 'sendgrid-template-id',
substitutions: {
name: 'Some One',
id: '123',
},
};
Alternatively, you may specify the substitution wrappers via the data object as well. This will override any wrappers you may have configured globally.
const data = {
templateId: 'sendgrid-template-id',
substitutionWrappers: ['{{', '}}'],
substitutions: {
name: 'Some One',
id: '123',
},
};
Customization per recipient
To send multiple individual emails to multiple recipients with additional customization (like a different subject), use the personalizations
field as per the API definition instead of to
, leveraging all customization options:
const data = {
personalizations: [
{
to: 'recipient1@example.org',
subject: 'Hello recipient 1',
substitutions: {
name: 'Recipient 1',
id: '123',
},
headers: {
'X-Custom-Header': 'Recipient 1',
},
customArgs: {
myArg: 'Recipient 1',
},
},
{
to: 'recipient2@example.org',
subject: 'Hello recipient 2',
substitutions: {
name: 'Recipient 2',
id: '456',
},
headers: {
'X-Custom-Header': 'Recipient 2',
},
customArgs: {
myArg: 'Recipient 1',
},
sendAt: 1500077141,
}
],
from: 'sender@example.org',
text: 'Hello plain world!',
html: '<p>Hello HTML world!</p>',
};
If the substitutions
field is provided globally as well, these substitutions will be merged with any custom substitutions you provide in the personalizations
.
Sending attachments
Attachments can be sent by providing an array of attachments
as per the API specifications:
const data = {
to: 'recipient@example.org',
from: 'sender@example.org',
subject: 'Hello attachment',
html: '<p>Here’s an attachment for you!</p>',
attachments: [
{
content: 'Some attachment content',
filename: 'some-attachment.txt',
},
],
};
Manually providing content
Instead of using the text
and html
shorthand properties, you can manually use the content
property:
const data = {
to: 'recipient@example.org',
from: 'sender@example.org',
subject: 'Hello manual content',
content: [
{
type: 'text/html',
value: '<p>Hello HTML world!</p>',
},
{
type: 'text/plain',
value: 'Hello plain world!',
},
],
};
Specifying time to send at
Use the sendAt
property to specify when to send the emails (in seconds, not milliseconds):
const data = {
to: 'recipient@example.org',
from: 'sender@example.org',
subject: 'Hello delayed email',
html: '<p>Some email content</p>',
sendAt: 1500077141,
};
Use the headers
property to specify any custom headers:
const data = {
to: 'recipient@example.org',
from: 'sender@example.org',
subject: 'Hello custom header',
html: '<p>Some email content</p>',
headers: {
'X-CustomHeader': 'Custom header value',
},
};
Specifying categories
Use the categories
property to provide an array of categories for your email:
const data = {
to: 'recipient@example.org',
from: 'sender@example.org',
subject: 'Hello email with categories',
html: '<p>Some email content</p>',
categories: [
'transactional', 'customer', 'weekly',
],
};
Specifying a single category
is also supported:
const data = {
to: 'recipient@example.org',
from: 'sender@example.org',
subject: 'Hello email with categories',
html: '<p>Some email content</p>',
category: 'transactional',
};
Other options
All other options from the API definition are supported:
const data = {
sections: {},
customArgs: {},
batchId: String,
asm: {},
ipPoolName: String,
mailSettings: {},
trackingSettings: {},
};
Kitchen sink example
An example with most settings used (note that some settings can be used in multiple ways, see above for full details for each setting):
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const data = {
to: 'recipient@example.org',
cc: 'someone@example.org',
bcc: ['me@example.org', 'you@example.org'],
from: 'sender@example.org',
replyTo: 'othersender@example.org',
subject: 'Hello world',
text: 'Hello plain world!',
html: '<p>Hello HTML world!</p>',
templateId: 'sendgrid-template-id',
substitutionWrappers: ['{{', '}}'],
substitutions: {
name: 'Some One',
id: '123',
},
attachments: [
{
content: 'Some attachment content',
filename: 'some-attachment.txt',
},
],
categories: ['Transactional', 'My category'],
sendAt: 1500077141,
headers: {
'X-CustomHeader': 'Custom header value',
},
sections: {},
customArgs: {
myCustomArg: 123,
},
batchId: 'sendgrid-batch-id',
asm: {},
ipPoolName: 'sendgrid-ip-pool-name',
mailSettings: {},
trackingSettings: {},
};
sgMail
.send(data)
.then(() => console.log('Mail sent successfully'))
.catch(error => console.error(error.toString()));