Bootstrap FreeKB - Node.js - Send email using nodemailer
Node.js - Send email using nodemailer

Updated:   |  Node.js articles

The nodemailer package can be used to send email in Node.js. The npm list command can be used to determine if you have the nnodemailer package installed. If not, the npm install command can be used to install the nodemailer package. Once installed, your package.json should include the nodemailer package.

{
  "dependencies": {
    "nodemailer": "^6.9.14"
  }
}

 

If your package.json file does not have "type": "module" this should mean you are using CommonJS. In this scenario, you would use "require" to import nodemailer.

const nodemailer = require('nodemailer');

 

And here is a basic example of how to send an email.

import nodemailer from 'nodemailer';

const transporter = nodemailer.createTransport({
  host: "smtp.example.com",
  port: 465,
  secure: true, // Use true for port 465, use false for all other ports
  auth: {
    user: "john.doe@example.com",
    pass: "itsasecret",
  },
});

async function main() {

  const info = await transporter.sendMail({
    from: '"John Doe" <john.doe@example.com>',
    to: "jane.doe@example.com, jack.doe@example.com",
    subject: "my Subject Line",
    text: "Hello Text",
    html: "<b>Hello HTML</b>",
  });
  console.log("Message sent: %s", info.messageId);
}

sendEmail()
  .then(
    response => {
      console.log(response)
      console.log("Message sent: %s", info.messageId);
    }
  )
  .catch(
    err => {
      console.log(err)
      process.exit(1)
    }
  )

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 8bc3ff in the box below so that we can be sure you are a human.