Sending emails in code and tests
How to send emails and attachments in code and tests.
You can send emails from any MailSlurp inbox that you have created.
Free MailSlurp accounts cannot send emails to some common email domains such as gmail
and yahoo
(paid accounts aren't affected). This is to reduce spam.
To send emails to all addresses please use a paid account or contact support. For more information see the sending limits page.
Basic
The simplest email you can send only requires a recipient and an inbox.
await mailslurp.sendEmail(inboxId, {
to: [recipientEmail],
});
This will send an empty email from the inboxes email address to the recipient. Most emails however are more complicated than this. Let us see the options next.
For all sending options see the SendEmailOptions reference docs. For forwarding and auto-forwarding rules see the forwarding guide.
Options
From and reply-to
Emails have a reply-to
and from
header. Emails use the inbox email address by default for from
and reply-to
. You can set these as options:
await mailslurp.sendEmail(inbox.id, {
to: [recipientEmail],
// can include names in addresses in the format below
replyTo: '"Support" <support@my-ap.com>',
// quote the property if a reserved word
['from']: inbox2.emailAddress,
});
Setting custom from
headers is not recommended if you wish to maintain a good spam rating. You should instead set an inbox's name
property and that will be included in the headers automatically along with the inbox's email address.
Recipients
You can provide to
, cc
, and bcc
recipient lists. Each must be in array format.
Example:
await mailslurp.sendEmal(inbox.id, {
// use lists of email addresses
to: ["user1@hexample.com"],
cc: ["a@1.com", "b@2.com"],
// to specify a name use quotes `"` and angle brackets `<` and `>` in the named style
from: [`"Admin Desk" <${inbox.emailAddress}>`]
});
Recipient format
Each recipient must be a valid email address and can either be specified directly or with a name:
- Plain format:
hello.team@myapp.com
- Named format:
"Sender Name" <sender@example.com>
Internationalization
If your email address uses special characters encode it first using Punycode local encoding on part before the @
sign.
张伟@mydomain.com
= xn--cpqy30b@mydomain.com
Subject line
You can specify subject as follows:
await mailslurp.sendEmal(inbox.id, {
to: ["me@test.com"],
subject: "my subject line",
});
Body
The body of an email is a string. If the body includes HTML set html: true
to ensure the correct content-type
header is used with the email.
await mailslurp.sendEmal(inbox.id, {
to: ["me@test.com"],
body: "Hi there",
});
You can specify character encoding with the charset option, eg: charset: "utf8"
. See i18n guide for more information.
HTML encoding
You can also send HTML by setting html: true
. All emails are UTF-8 by default and [support i18n].
Here is a full example with multiline HTML and UTF8 characters.
await mailslurp.sendEmal(inbox.id, {
to: ["me@test.com"],
body: `
<article>
<h1>γειά σου κόσμος</h1>
</article>
`,
charset: "utf8",
html: true,
});
When sending HTML you should use tables and inlined CSS for better rendering in most clients.
Attachments
You can submit a list of attachment IDs when sending emails to attach files. You must upload the files before sending using the attachment upload endpoints.
// first upload attachments as base64 encoded string
const fs = require('fs');
const file = {
base64Contents: Buffer.from(
fs.readFileSync(attachmentPath, { encoding: 'base64' })
).toString(),
contentType: 'image/png',
filename: 'pixel.png',
};
const [attachmentId] = await mailslurp.uploadAttachment(file);
// send email with attachment ID in array
await mailslurp.sendEmail(inbox.id, {
to: [emailAddress],
attachments: [attachmentId],
});
Encoding
MailSlurp expects files as base 64 encoded strings. You can do this by reading a file as bytes and then converting those to base64. Here is an example using NodeJS:
import { readFileSync } from "fs";
const bytes = readFileSync(path);
const base64Contents = new Buffer(bytes).toString("base64");
Bounce rate and reputation
When you send emails from a free account Mailslurp monitors email bounces. A bounce is when an email is rejected by an email provider. To avoid bounce warnings upgrade to a paid account. To ensure your account always delivers emails regardless of bounce status or payment failures use queue-backed email sending or see the section below.
Sending emails with a queue
MailSlurp supports sending emails using SQS-backed message queues. This means that outbound emails are placed on a queue and can be retried and recovered if sending is blocked for your account or a recipient is not accepting messages. Check your plan for feature support.
await mailslurp.inboxController.sendEmailWithQueue({
inboxId: inboxId,
sendEmailOptions: {
to: [recipient],
subject: 'Sent with a queue',
body:
'Use queues to allow recovery of failed email ' +
'sending when account reaches limits or has payment issues',
},
// validate before adding to queue to fail early
validateBeforeEnqueue: false,
});
Templates
MailSlurp supports sending emails with predefined templates.
Capabilities
Templates can be created in code or designed in the dashboard. Templates support HTML, variables, and handlebars templating syntax. Unlike other services MailSlurp will warn you if you try to send a template with missing variables.
Creating templates
MailSlurp supports email templates for sending automated emails with variable replacements.
await mailslurp.templateController.createTemplate({
createTemplateOptions: {
name: 'Welcome',
content: 'Welcome to our app',
},
});
Variable syntax
If you want to use variables in your templates simple wrap each variable in double curly braces:
const template = await mailslurp.templateController.createTemplate({
createTemplateOptions: {
name: 'Welcome email',
content: 'Hello {{firstName}}. Welcome to {{brandName}}.',
},
});
expect(template.id).toBeTruthy();
expect(template.variables).toEqual([
{
name: 'firstName',
variableType: TemplateVariableVariableTypeEnum.STRING,
},
{
name: 'brandName',
variableType: TemplateVariableVariableTypeEnum.STRING,
},
]);
MailSlurp will recognize the firstName
and brandName
variables which can then be supplied as a map of templateVariables
in sendEmail()
methods. They will also be displayed in the dashboard:
Passing variable values
When you send an email with a template you can pass a map of template variables and values.
const templateObject = await mailslurp.templateController.getTemplate({
templateId,
});
expect(templateObject.content).toContain(
'Hello {{firstName}}. Welcome to {{brandName}}.'
);
const sent = await mailslurp.sendEmail(inboxId, {
to: [emailAddress],
subject: 'Welcome {{firstName}}',
template: templateId,
templateVariables: {
firstName: 'Sally',
brandName: 'My Company',
} as any,
});
expect(sent.subject).toContain('Welcome Sally');
expect(sent.body).toContain('Hello Sally. Welcome to My Company.');
MailSlurp will validate emails and return an error if passed variable names do not match template variables.
Contacts and groups
MailSlurp also supports contact and contact groups. You can create these in the dashboard.
To send an email to a contact use the toContacts
property:
await mailslurp.sendEmail(inbox.id, { toContacts: [contactId1, contactId2] });
To send emails to each contact in a group use the toGroup
property.
await mailslurp.sendEmail(inbox.id, { toGroup: groupId });
Next Steps
Related content
Send attachments with an Email API
How to send email attachments using MailSlurp API.
MailSlurp Send Limits
How to manage sending limits and spam detection
Sending emails in code and tests
How to send emails and attachments in code and tests.