Contents
Requirements to send an email with nodemailer under NodeJS
Install nodemailer from npm : https://www.npmjs.com/package/nodemailer
To receive mail locally: https://github.com/maildev/maildev (Useful tools to install globally)
To receive mail locally with maildev
To receive mail with maildev, you must first launch maildev after installing it globally (npm i maildev -g), then go to a command prompt to type maildev
Send the mail with nodemailer
You will need to import nodemailer with the require command.
Then create a transporter with the development or production info (you define it) for developments we send locally to maildev (See options transporter).
Then we define the options of the mail namely, from whom the mail comes, to whom we send it, the subject, the text and HTML format: See more options
Launch the NodeJS script and the mail will be sent (node index.js in my case)
//You have to import nodemailer const nodemailer = require('nodemailer') //We connect to the transporter with different options depending on the environment let transporter = null if (process.env.NODE_ENV === 'prod') { transporter = nodemailer.createTransport({ host: 'your host', port: 'your port', secure: false, auth: { user: 'the user of smtp', password: 'the password', }, }) } else { transporter = nodemailer.createTransport({ host: 'localhost', port: 1025, secure: false, tls: { // do not fail on invalid certs rejectUnauthorized: false, }, }) } // Async function to wait mail sending async function sendMail() { const mailOptions = { from: 'from@email.fr', to: 'to@email.fr', subject: 'Test email for the tutorial', text: "Here is the text of the test email", //The texte content of the mail html: "<h1>HTML</h1><p>Here is the text in a paragraph for the test email</p>", // The html content } await transporter.sendMail(mailOptions) } //We send mail sendMail()
Viewing mail with maildev
When you launch maildev with the command prompt you see this message that tells you which port the SMTP server is pointing to and where to view the mail, so go to localhost:1080 to see the maildev interface
MailDev webapp running at http://0.0.0.0:1080 MailDev SMTP Server running at 0.0.0.0:1025
Here is the maildev interface to receive your mails.
The tutorial is finished, thanks for reading.