Intro
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
- 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: 'smtp.ethereal.email',
    port: 587,
    secure: false,
    auth: {
      user: 'yutfggtgifd7ixet@ethereal.email',
      pass: 'tX29P4QNadD7kAG7x5'
    }
  },
  mail: {
    from: 'foo@example.com',
    to: 'bar@example.com',
    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)}`);
};
sendMail(config).catch(console.error);
Note: Nodemailer has a lot of available settings, therefore read the docs of nodemailer.
Run it from the terminal
- Run it:
node index.js
- Result:
Preview: https://ethereal.email/message/XWk2jZDkEStePsCvXWk60Yf74VUAhgNZAAAACQqQo2lpzFsxaciWAqd9ZjY
Further Reading
Questions
- What is your favorite way/package to send mails in Node?
- Do you automate some tasks with node emails?
 

 
    
Top comments (1)
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.