Blog

How to Send Emails in Node.js: SMTP, APIs, and Courier

Adeyinka AdegbenroAdeyinka AdegbenroFebruary 23, 2021
How to send email in NodeJS

Nearly every modern web app needs to send transactional emails in response to user activity: account creation, password resets, order confirmations, or verification codes.

If you're building with Node.js, there are three common ways to send them:

  1. SMTP: Connect to a mail server, your own or a provider's, with a library like Nodemailer
  2. Email API: Use a hosted provider like SendGrid or Mailgun for faster setup and better deliverability
  3. Notification service: Use a multichannel service like Courier to centralize message design, logic, and delivery (see our SendGrid + Node.js tutorial)

1. Using SMTP

Simple Mail Transfer Protocol (SMTP) is the standard protocol mail servers use to pass email to each other, and the one your app uses to hand a message to a server for delivery.

When you send from a client like Gmail, the client hands the message to Gmail's SMTP server, which finds the recipient's mail server and relays the message there.

Advantages of using SMTP

  • Widely supported: SMTP is a universal standard. Libraries like Nodemailer make it straightforward to set up, and nearly every email provider accepts it.
  • Complete control: Running your own SMTP server gives you full control over how messages are composed, authenticated, and sent, without relying on third-party services.

Drawbacks of using SMTP

  • Security concerns: SMTP is inherently insecure without proper authentication and encryption. It’s vulnerable to spam, spoofing, and data breaches unless hardened with TLS, SPF, DKIM, and DMARC.
  • Complex maintenance: Hosting your own mail server means you own uptime, spam filtering, and deliverability. You probably don't want that job long term.
  • Slower performance and limited feedback: Each message takes several round trips (EHLO, STARTTLS, AUTH, MAIL FROM, RCPT TO, DATA), where an API call is one HTTPS request. A bounce can also arrive later as an email instead of an error your code sees.
  • Reliability issues: Your server’s IP may be blocklisted, or firewalls might block required ports, leading to delivery failures without clear diagnostics.

🛠️ If you choose to go the SMTP route, use a sandbox service like Mailtrap for safe testing, and make sure your production server is configured with secure defaults.

2. Using an Email API

Email APIs let you send messages from your application through a hosted provider, without running your own mail server. They handle message assembly, delivery, and reputation management for you.

Popular email API services include:

Advantages of using an Email API

  • Fast setup: An SDK and an API key are all you need to send.
  • Highly scalable: Built to support high-volume workloads with built-in queuing and retry mechanisms.
  • Better deliverability: Providers maintain sending IPs and reputations to help your messages land in the inbox.
  • More secure: API keys you can scope and revoke replace a mailbox password, and every call goes over HTTPS.

Drawbacks of using an Email API

  • Third-party dependency: You’re outsourcing message delivery to a provider. If their service goes down or they change pricing, you feel it.
  • Limited channel coverage: If your app needs to notify users through additional channels like SMS, push, chat apps (e.g., Slack, Microsoft Teams, Discord), or in-app inboxes, you’ll have to integrate and manage each of those channels separately.
  • Vendor lock-in risk: Switching providers often means rewriting templates or updating your integration logic, especially if you're deeply tied to one API's format or features.

Before choosing a provider, compare key features, delivery performance, uptime SLAs, and support for your use case.

3. Using a Notification Service

A notification service like Courier sits on top of your email API or SMTP server and adds what surrounds the send: templates, routing, user preferences, and logs, across every channel.

You bring your own provider for each channel. For email, that could be your own SMTP server or a hosted email API like SendGrid, Postmark, or Amazon SES. Courier can fail over to another provider if one becomes unavailable.

Adding a channel or switching providers doesn't change your app's code: it keeps making the same send call, whether the message goes out by email, SMS, push, or a chat app like Slack or WhatsApp.

Advantages of using a multichannel notification service

  • Send options: Send from the API or from a Journey, or send a one-time broadcast from the dashboard
  • Multichannel routing: Route delivery across channels like email, push, SMS, chat apps (e.g., Slack, Teams), or in-app inboxes
  • Unified logging and analytics: View all delivery logs across channels and providers in one place
  • User preferences: Built-in logic and hosted UI for users to manage notification topics, channels, and frequency
  • Send limits and throttling: Prevent spam or over-notification
  • Batching and digesting: Bundle related content into a single digest based on rules or user preferences
  • Integrations: Connect to email, SMS, push, and chat providers, plus customer data platforms like Segment

Teammates who don't write code can edit content, styling, or branding in Courier, and you can preview notifications with test data in a separate Test environment before going live.

Drawbacks of using a multichannel notification service

You still deliver through an email API or SMTP server underneath, so their outages still matter. Courier reduces that risk with:

  • Provider failover: e.g., fall back to Postmark if SendGrid is down
  • Channel failover: e.g., fall back to SMS or push if email can't be delivered

Tutorial: How to send emails with Nodemailer and SMTP

Nodemailer is a Node.js module for sending email. You can use it to create HTML or plain-text emails, add attachments, and send through different transport methods, including built-in SMTP support. Nodemailer 10 and later require Node.js 20 or newer.

Start by creating a Node.js project:

Terminal
mkdir email-nodeapp && cd email-nodeapp
npm init -y

The -y flag accepts npm's defaults. Next, install Nodemailer:

Terminal
npm install nodemailer

The examples use ES modules with top-level await, so save each file with an .mjs extension.

Nodemailer’s createTransport function sets how mail goes out. For SMTP, it takes a host, a port, and credentials.

To get a host URL, you need an SMTP server. For development, you can use Mailtrap, or a similar service, as a fake SMTP server. A fake SMTP server lets you avoid cluttering your real account with multiple tests while still seeing how your test emails behave: do all the buttons work the way they’re supposed to, is the formatting still correct after sending, and so on.

Create a Mailtrap account if you don’t already have one. In the Integrations dropdown on the dashboard, select Nodemailer and copy the credentials displayed.

Creating a Mailtrap account to test Nodemailer

Create an email.mjs file and add the following:

JavaScript
import nodemailer from "nodemailer";

const transporter = nodemailer.createTransport({
  host: "smtp.mailtrap.io",
  port: 2525,
  auth: {
    user: "<user>",
    pass: "<pass>",
  },
});

Substitute the host, user, and password with the Mailtrap credentials you copied from the dashboard above. Now you can send an email with the transporter’s sendMail method.

Append the following to email.mjs:

JavaScript
const message = {
  from: "from-example@email.com",
  to: "to-example@email.com",
  subject: "Subject",
  text: "Hello SMTP Email",
};

try {
  const info = await transporter.sendMail(message);
  console.log(info);
} catch (err) {
  console.log(err);
}

For an HTML email, add an html property. Keep text too: Nodemailer sends both, and clients that don't render HTML show the plain-text version.

JavaScript
const message = {
  from: "from@email.com",
  to: "to@email.com",
  subject: "Subject",
  text: "Hello SMTP Email",
  html: "<h1>Hello SMTP Email</h1>",
};

Run it:

Terminal
node email.mjs

Go to your Mailtrap dashboard to see your email was received.

Check the delivery status of your email in your Mailtrap dashboard

Tutorial: How to send emails using a transactional email API

This tutorial uses SendGrid. SendGrid no longer has a free plan, but its 60-day trial lets you send 100 emails a day.

Sign up for SendGrid, then create an API key. Go to Settings > API Keys in the SendGrid console, click “Create API Key,” and give the key a name. For permissions, choose “Custom Access” and grant Mail Send only, so a leaked key can't change anything else on your account. Click “Create & View,” then copy the key.

Next, install the SendGrid JavaScript client with npm:

Terminal
npm install @sendgrid/mail

Set your API key as an environment variable:

Terminal
export SENDGRID_API_KEY="<SENDGRID_API_KEY>"

Create a file in your project directory named sendgrid.mjs and add the following:

JavaScript
import sendgrid from "@sendgrid/mail";

sendgrid.setApiKey(process.env.SENDGRID_API_KEY);

const msg = {
  to: "test@example.com", // Change to your recipient
  from: "test@example.com", // Change to your verified sender
  subject: "Sending with SendGrid Is Fun",
  text: "and easy to do anywhere, even with Node.js",
  html: "<strong>and easy to do anywhere, even with Node.js</strong>",
};

try {
  const [response] = await sendgrid.send(msg);
  console.log("Email sent, status:", response.statusCode);
} catch (error) {
  console.error(error);
}

The from address must be a verified sender identity, which you create under Settings > Sender Authentication. Set to to an inbox you can check.

Run it:

Terminal
node sendgrid.mjs

Then open “Activity” in the SendGrid console to see the message and whether it was delivered.

Tutorial: How to send emails using a multichannel notification service

Courier is a multichannel notifications platform: one API for email, SMS, push, in-app, and chat. You can bring your own email service provider, including SMTP, or any of the popular email APIs like SendGrid, Amazon SES, and Postmark.

To start using Courier, create an account. The Developer plan includes 10,000 messages a month free. A new workspace's Test environment comes with a test email provider already set up, so you can send before you connect your own. It delivers only to the address you signed up with, so use that address as the recipient in this tutorial.

Make sure the environment dropdown at the top of the console says Test. Then follow these steps:

  1. Create a template. Open Templates, select Add template, and choose Design Studio v2. Name it and create it.
  2. Design the email. Select the Email channel tab. The routing selector in the toolbar sets which provider delivers it, and in Test the Courier Test Email Provider is already connected. Drag in a Text block and write Hi {{data.name}}, welcome aboard. Courier auto-saves as you edit. Other blocks (Button, Image, Heading) work the same way, and variables like {{profile.email}} and {{data.x}} work anywhere in the content.
  3. Publish and copy the template ID. Select Publish, then copy the Template ID from the top of the editor.
  4. Copy your Test API key. Go to Settings → API Keys in the console and copy your Test key. Keep it server-side, in an environment variable rather than in your code.
Terminal
export COURIER_API_KEY="<YOUR_TEST_API_KEY>"

Next, install the Courier Node.js SDK, @trycourier/courier:

Terminal
npm install @trycourier/courier

Create a file in your project directory named courier.mjs and add the following:

JavaScript
import Courier from "@trycourier/courier";

const courier = new Courier({ apiKey: process.env.COURIER_API_KEY });

const { requestId } = await courier.send.message({
  message: {
    to: { email: "<EMAIL_ADDRESS>" },
    template: "<TEMPLATE_ID>",
    data: { name: "Ada" },
  },
});

console.log("Email sent, request ID:", requestId);

The send.message call takes a message object with three fields:

  • to: who receives the email. For a user you've stored in Courier, pass { user_id: "<USER_ID>" } instead.
  • template: the Template ID you copied from Design Studio. You can also create an alias for it.
  • data: the values merged into your template. Here, name fills {{data.name}}.

Run it:

Terminal
node courier.mjs

For a single recipient, the requestId it prints is also the message ID. To check the email's status, open Logs in the Courier console. Logs lists every message in the current environment, newest first, with its status. Open a message to see its timeline, including any error.

When you're ready to go live, create a Production key in Settings → API Keys, copy the template over with Migrate assets, and connect your own email provider in Production. Integrations don't carry over from Test, and a Test key's sends only show up in Test logs. See environments and API keys for details.

Conclusion

If email is all you need, Nodemailer or an email API like SendGrid gets you sending quickly. If you expect to add SMS, push, Slack, or an in-app inbox later, or want teammates who don't write code to edit the content, Courier keeps it in one place: bring your own email provider (SMTP or API), design notifications visually or in code, and add channels through the same API.

Sign up for Courier and start building multichannel notifications.