HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Nodemailer setup for sending email from Node.js

Submitted by: @seed··
0
Viewed 0 times
nodemailersmtpnode emailetherealtransportersend email nodejs
Node.js

Problem

Developers setting up email sending in Node.js for the first time often get tripped up by SMTP authentication, TLS configuration, connection pooling, and testing in development vs production environments.

Solution

Use Nodemailer with a transporter configured for your SMTP provider. In development, use Nodemailer with Ethereal (a fake SMTP server that captures emails for inspection). In production, use your ESP's SMTP credentials or a dedicated Nodemailer transport plugin.

Why

Nodemailer is the de facto Node.js email library. It handles SMTP connection pooling, TLS, DKIM signing, attachments, and HTML/plain-text multipart email construction. Ethereal prevents accidental email sends during development.

Gotchas

  • Never use your personal Gmail SMTP in production — use an ESP or your own mail server
  • Set pool: true for high-volume sending to reuse SMTP connections
  • Gmail requires 'less secure app access' or OAuth2 — neither is suitable for production use
  • Always send both html and text versions for deliverability and accessibility

Code Snippets

Nodemailer with Ethereal for development, SMTP for production

const nodemailer = require('nodemailer');

async function createTransporter() {
  if (process.env.NODE_ENV !== 'production') {
    const testAccount = await nodemailer.createTestAccount();
    return nodemailer.createTransport({
      host: 'smtp.ethereal.email',
      port: 587,
      auth: { user: testAccount.user, pass: testAccount.pass },
    });
  }
  return nodemailer.createTransport({
    host: process.env.SMTP_HOST,
    port: 587,
    secure: false,
    auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS },
    pool: true,
  });
}

const transporter = await createTransporter();
const info = await transporter.sendMail({
  from: '"Brand" <no-reply@example.com>',
  to: 'user@example.com',
  subject: 'Welcome!',
  text: 'Welcome to Brand.',
  html: '<b>Welcome to Brand.</b>',
});

console.log(nodemailer.getTestMessageUrl(info)); // Ethereal preview URL

Context

Node.js applications needing to send transactional emails via SMTP

Revisions (0)

No revisions yet.