Send emails in NodeJS using SMTP

How to use Javascript SMTP client (or Nodemailer) to send email with MailSlurp mail server

send email in javascript

NodeJS provides many functions for sending email using SMTP. One common approach is to use nodemailer in conjunction with an email provider such as MailSlurp.

Setting up

First create a free email account on MailSlurp and get your API Key. Then create a new project and install the following dependencies:

npm init -y
npm install --save nodemailer mailslurp-client debug jest

Create a test to send email

Next we can configure nodemailer in a test using MailSlurp's SMTP server credentials.

const nodemailer = require("nodemailer")
const {MailSlurp, CreateInboxDtoInboxTypeEnum} = require('mailslurp-client');
const log = require('debug')('ms:smtp')

describe('node mailer smtp usage', () => {
let config;

    beforeAll(() => {
        // provide a mailslurp API KEY
        const apiKey = process.env.API_KEY;
        expect(apiKey).toBeTruthy();
        // create config for clients and main class
        config = {apiKey};
    });

    it('can create smtp inbox then send email to it with nodemailer', async () => {
        log("Create inbox")
        const mailslurp = new MailSlurp(config);
        const inbox = await mailslurp.createInbox();
        expect(inbox.id).toBeTruthy();
        expect(inbox.emailAddress).toContain('@mailslurp.com');

        log("Start transport")
        const transport = nodemailer.createTransport({
            host: "mx.mailslurp.com",
            port: 2525,
            secure: false
        })

        const sent = await transport.sendMail({
            from: '"Fred Foo ๐Ÿ‘ป" <foo@example.com>',
            to: inbox.emailAddress,
            subject: "Hello โœ”",
            text: "Hello world?",
            html: "<b>Hello world?</b>",
        });
        log("Email sent")
        expect(sent.messageId).toBeTruthy()

        log("Wait for latest")
        const email = await mailslurp.waitForLatestEmail(inbox.id, 30000, true)
        expect(email.subject).toContain("Hello")
        expect(email.isHTML).toBeTruthy()
    });


    it('can create smtp inbox then send email from a mailslurp address', async () => {
        log("Try plain auth")
        const mailslurp = new MailSlurp(config);
        const inbox = await mailslurp.createInboxWithOptions({inboxType:CreateInboxDtoInboxTypeEnum.SMTP_INBOX});
        const server = await mailslurp.getImapSmtpAccessDetails()

        log("Fetched imap smtp access")
        expect(inbox.id).toBeTruthy();
        expect(inbox.emailAddress).toContain('@mailslurp.mx');

        const opts = {
            host: server.smtpServerHost,
            port: server.smtpServerPort,
            secure: false,
            auth: {
                user: server.smtpUsername,
                pass: server.smtpPassword,
                type: "PLAIN"
            },
        }
        log("Create auth plain transport")
        const transport = nodemailer.createTransport(opts)

        log("Send email")
        const sent = await transport.sendMail({
            from: inbox.emailAddress,
            to: inbox.emailAddress,
            subject: "Test outbound email",
            text: "Can I send on behalf?",
            html: "<b>Hello world</b>",
        });
        expect(sent.messageId).toBeTruthy()

        log("Wait for email to arrive")
        const email = await mailslurp.waitForLatestEmail(inbox.id, 30000, true)
        expect(email.subject).toContain("Test outbound")
        expect(email.isHTML).toBeTruthy()
    });
});

More examples

To see more examples of sending email using NodeJS see the examples page.

Related content

Fake SMTP servers for safe testing that prevent any outbound emails from reaching real users

Test emails safely with no risk of spamming users with real emails

Java email library for SMTP and creating email addresses

MailSlurp Java SDK for sending and receive email and attachments on the JVM.

NodeJS MailSlurp SDK

Nodemailer alternatives to send and receieve email in code and tests

SMTP email application libraries

How to send email in CSharp, PHP, Ruby, Java, Python, and NodeJS using the SMTP protocol and MailSlurp mailservers.

1111 SMTP Connections failing

1111 SMTP Connections failing

Fastest way to start a typescript project

Modern typescript tooling has come a long way. See how to setup a new project with TS-Node, TSC, and typeconfig.json.

Fetch error message javascript

Handle response exceptions with Fetch in Javascript

GraphQL API disposable email accounts

How to create real email addresses using GraphQL to send and receive emails in tests and frontend applications.

GraphQL Email API Tutorial

Did you know you can send and receive emails using GraphQL?

How to Send an Email in Python

Send emails using SMTP mailer in Python. Detailed tutorial for sending mail in Python.

Hugo responsive image srcsets

Serve responsive picture tags with custom render-image layout partial in Hugo static site generator.

How to send emails in Javascript (NodeJS)

JS SMTP email sending guide using HTML and NodeJS.

NodeMailer NPM Tutorial

Send and receive email using NodeMailer in Node JS.

PHPMailer tutorial (Sending email with PHP)

PHPMailer tutorial (Sending email with PHP)

How to send an email using Powershell (Windows and cross-platform)

Use Send-MailMessage in Windows Powershell to send emails using an SMTP server or MailSlurp's free email API.

How to send email in R

RLang tutorial for sending emails over SMTP.

SMTP Commands and Response Codes List

A full list of commands and response status codes for SMTP mail servers when sending emails.

Create custom print classes with Tailwind

Configure tailwind.config.js to create prefixed classes with a custom media query.

Test SMTP servers with Telnet

How to use Telnet to test the SMTP servers?

What Is Amazon Simple Storage Service (SES) - And How Can I Use It?

Amazon SES is an email service among virtual servers, AI apps, and libraries. Ideally, you can integrate your email system with your program hosted on Amazon.

Grab all details about an SMTP Port

What are common SMTP mail server ports and how do you find them?

Which SMTP Port Should I Use?

Picking the right port for SMTP mailservers

CypressJS Example

Test email sign-up, password verification and more with Cypress JS and MailSlurp. Capture OTP magic links and test auth flows end-to-end.

CypressJS Email Testing

Use real email accounts in CypressJS to test user sign-up, email verification, and more.

Jest, Puppeteer

Test email accounts in React with Jest and Puppeteer. Send and receive emails in Javascript.

Webdriver, JS, WDIO

Test email related processes like sign-up and verification using WDIO WebDriver and MailSlurp.

TestCafe end-to-end MFA testing for user sign-up and email verification

End-to-end testing with MailSlurp, NodeJS, and TestCafe.

Avoiding email spam filters

How to send emails that don't trigger a spam warning.

Base64 file uploads

How to encode files as Base 64 encoded strings in several languages

BCC and CC in SMTP emails

What is cc and bcc in email? What is the difference between cc and bcc?

BCC For Email: What It Means And When To Use It

What is BCC email field (blind carbon copy) and how does it differ to CC?

What Is The Best SMTP Port To Use?

MailServers use TCP ports to transmit emails. Picking the right port between 25 vs 2555, 465 vs 587 in SMTP is easy with this guide.

How to configure Mail desktop clients with MailSlurp

How to setup MailSlurp with Outlook, Gmail, Thunderbird, Mail app and more.

Send email with CSharp using SMTP Client and MailSlurp

Create a custom SMTP client and access MailSlurp inboxes from CSharp/DotNET.

Deno Email Apis

Send and receive emails in Deno JS. Use APIs in Deno with MailSlurp.

DMARC โ€“ All Facts that you should know

DMARC โ€“ All Facts that you should know

Email read (opened seen settings)

How to control the seen or read settings for an email using MailSlurp.

Email size limits

Email size limits

The Fundamentals Of Email Subdomains

How to manage email subdomain custom mailboxes using SMTP/IMAP mailserver settings.

GraphQL Email API

Fetch and read emails with GraphQL inboxes using MailSlurp email API.

How to send emails in VBA

Send email in Visual basic

Testing OTP password link username and password for 2 factor authentication (2FA)

Testing OTP password link username and password for 2 factor authentication (2FA)

A guide to PHP Mailer

A guide to PHP Mailer

SMTP IMAP Settings

How to access MailSlurp email accounts using IMAP and SMTP servers

MailSlurp NodeMailer SMTP Usage

Use SMTP nodemailer with MailSlurp disposable email addresses

SMTP Relay for outbound smtp servers

How to use SMTP relay to address spam and security issues that affect outbound mail servers.

SMTP vs HTTP MailSlurp inboxes

The difference between HTTP and SMTP inboxes and domains in MailSlurp.

Testing email with Cypress test email accounts

Test email accounts for CypressJS. End-to-end testing with real email addresses using MailSlurp Cypress plugin.

What are SMTP ports

What are SMTP ports

CSharp send SMTP email

How to use CSharp SMTP client to send email with MailSlurp mail server

Send SMTP email with Java

How to use Java SMTP client to send email with MailSlurp mail server on the JDK

Send emails in NodeJS using SMTP

How to use Javascript SMTP client (or Nodemailer) to send email with MailSlurp mail server

Send SMTP emails with PHP

Use PHPMailer to send emails with SMTP and MailSlurp

Send SMTP email with Python (using SMTPLib)

How to send emails with Python's built-in SMTP client and MailSlurp mail servers.

Ruby send SMTP email

How to use Ruby SMTP client to send email with the MailSlurp mail servers

Testing Email with Cypress JS and MailSlurp

Email testing with Cypress JS

Ready to dive in?Start building email applications today.