Sending email in Javascript and NodeJS (Typescript examples)

Guide for sending emails in Javascript using an SMTP server or MailSlurp email API or SDK clients. Examples using NodeJS.

Sending email with MailSlurp is easy. Simply create an inbox and use the inbox's ID with sendEmail() methods.

Basics

The basic sendEmail() method has the following signature:

sendEmail(inboxId: string, sendEmailOptions: SendEmailOptions): Promise<Response>

Notice the inboxId. This is the inbox from which the emails will be sent. The second parameter contains properties describing the email to be sent.

Options

The only required property of SendEmailOptions is a to field — which is an array of email addresses.

{
  "to": ["user@mycompany.com"]
}

Other optional fields include the following:

interface SendEmaiOptions {
  to: Array<string>;

  // email subject
  subject?: string;

  // extra recipient fields
  cc?: Array<string>;
  bcc?: Array<string>;

  // email contents
  body?: string;

  // array of attachment IDs
  attachments?: Array<string>;

  // map of template variables to substitute in body
  templateVariables?: any;

  // optional headers
  charset?: string;
  replyTo?: string;
  from?: string;

  // is contents HTML?
  html?: boolean;
}

Example

await mailslurp.sendEmail(inboxId, { to: ["user@test.com"], body: "Hello" });

HTML and templates

You can flag { "html": true } when sending emails to indicate that HTML content is being sent. This is recommend if you want email providers to render markup correctly.

You can also pass a map of templateVariables when sending an email and MailSlurp will look for and interpret Moustache templates within your email body.

{
  "body": "Hello {{name}}",
  "templateVariables": {
    "name": "tester"
  }
}

Attachments

Next steps

That's how sending works at MailSlurp. Let's see it in action by finding the best MailSlurp library or integration for you application or tests.

Integrate MailSlurp &rarr