How to Test Sending SMTP Email locally with Nodemailer
codemonday
How to Test Sending SMTP Email locally with Nodemailer
move up
linefacebookx
move up
linefacebookx

How to Test Sending SMTP Email locally with Nodemailer

Jul 14, 2023
NodeJS

The local SMTP service with SMTP4Dev

Thanks to this repos https://github.com/rnwood/smtp4dev

This can receive and see the email content.

You can easily spin the service up with docker and go to localhost for the web admin.

docker run --rm -it -p 8090:80 -p 2525:25 rnwood/smtp4dev

There are two service :2525 is the SMTP service and :8090 on the web admin.

Nodemailer code

We use nodemailer to connect to the SMTP service.

const htmlMail = ... HTML string ...

const transporter = nodemailer.createTransport({
  host: process.env.SMTP_HOST,
  port: process.env.SMTP_PORT,
  secure: false, // upgrade later with STARTTLS
  tls: { rejectUnauthorized: false },
  auth: {
    user: process.env.SMTP_USERNAME,
    pass: process.env.SMTP_PASSWORD,
  },
});

await transporter.sendMail({
  from: 'test@example.com',
  to: 'test@example.com',
  subject: 'Test message title',
  html: htmlMail,
});

You can test it as script or bind it to GET /my-test-path to run it.

Then open the console to check the result

Bonus: Isolate testing of mock SMTP

How to know that SMTP is up and running?

$ telnet localhost 2525
Trying ::1...
Connected to localhost.
Escape character is '^]'.

220 419e193661e8 smtp4dev ready
HELO any-name
250 Nice to meet you
MAIL FROM:<foo@bar.com>
250 New message started
RCPT TO:<bar@baz.com>
250 Recipient accepted
DATA
354 End message with period
SUBJECT: This is subject
Hello,
Foo Bar Baz
Best regards,
Foo
.
250 Mail accepted
QUIT
221 Goodbye
Connection closed by foreign host.

CERT_HAS_EXPIRED Error: certificate has expired

Using normal unencrypted port need either

Globally set

process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

Or better set locally at Nodemailer

const transporter = nodemailer.createTransport({
...  
tls: { rejectUnauthorized: false }, <--- HERE
...
});

Hope this help !