Sending Emails with Nodemailer

  1. What is Nodemailer
  2. How to use Nodemailer
    1. Example
  3. Nodemailer for Strapi

What is Nodemailer

Nodemailer is a Node.JS npm module for sending emails. This has been the go to solution to most NodeJS developers for email delivery in their applications.

How to use Nodemailer

Execute the following command in the Node.js command prompt:

1
npm install nodemailer

or

1
yarn add nodemailer

Example

In this example, I am using Mailgun to send emails. You can sign up and get the STMP information required.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
"use strict";
const nodemailer = require("nodemailer");

// async..await is not allowed in global scope, must use a wrapper
async function main() {

// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: "smtp.mailgun.org",
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: 'YOUR MAILGUN USERNAME', // <= Input your username here
pass: 'YOUR PASSWORD', // <= Input your password here
},
});

// send mail with defined transport object
let info = await transporter.sendMail({
from: '"Admin" <[email protected]>', // sender address
to: "[email protected]", // list of receivers
subject: "Hi there", // Subject line
text: "Hello world?", // plain text body
html: "<b>Hello world with nodemailer</b>", // html body
});

console.log("Message sent: %s", info.messageId);
// Message sent: <[email protected]>
}

main().catch(console.error);

If you have your own custom domains, Zoho Mail provides a free plan with custom domain support, it supports SMTP protocol as well.

Nodemailer for Strapi

Strapi is an open-source headless CMS. There is a Nodemailer plugin you can use in your project.

In your console, excute the following command to install it:

1
2
3
4
5
# using yarn
yarn add @strapi/provider-email-nodemailer

# using npm
npm install @strapi/provider-email-nodemailer --save

Then edit the file config/plugins.js in your Strapi project:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
module.exports = ({ env }) => ({
// ...
email: {
config: {
provider: 'nodemailer',
providerOptions: {
host: env('SMTP_HOST', 'smtp.example.com'),
port: env('SMTP_PORT', 587),
auth: {
user: env('SMTP_USERNAME'),
pass: env('SMTP_PASSWORD'),
},
// ... any custom nodemailer options
},
settings: {
defaultFrom: '[email protected]',
defaultReplyTo: '[email protected]',
},
},
},
// ...
});

After that you will be able to view your Email configuration and test email delivery at the Strapi Dashboard: