DEV Community


Posted on • Updated on

NodeJS: How To Send An Email


So we installed NodeJS on our machine.

We also know How to Get External Packages.

Now we want to learn how to send an email using nodemailer.

Write a simple script

  • Open your terminal
  • Create a file named index.js:
touch index.js
Enter fullscreen mode Exit fullscreen mode
  • Add this JavaScript code into it:
// import nodemailer (after npm install nodemailer)
const nodemailer = require('nodemailer');

// config for mailserver and mail, input your data
const config = {
  mailserver: {
    host: '',
    port: 587,
    secure: false,
    auth: {
      user: '',
      pass: 'tX29P4QNadD7kAG7x5'
  mail: {
    from: '',
    to: '',
    subject: 'Hey',
    text: 'Testing Nodemailer'

const sendMail = async ({ mailserver, mail }) => {
  // create a nodemailer transporter using smtp
  let transporter = nodemailer.createTransport(mailserver);

  // send mail using transporter
  let info = await transporter.sendMail(mail);

  console.log(`Preview: ${nodemailer.getTestMessageUrl(info)}`);

Enter fullscreen mode Exit fullscreen mode

Note: Nodemailer has a lot of available settings, therefore read the docs of nodemailer.

Run it from the terminal

  • Run it:
node index.js
Enter fullscreen mode Exit fullscreen mode
  • Result:
Enter fullscreen mode Exit fullscreen mode

Further Reading


  • What is your favorite way/package to send mails in Node?
  • Do you automate some tasks with node emails?

Top comments (1)

stevetaylor profile image
Steve Taylor

Also take a look at mjml for creating emails that look consistent across numerous email clients with all their quirks. It’s an npm package and would work well in concert with nodemailer.