DEV Community

Cover image for How to Send Email in Node.js Using Nodemailer Package
Dina Pal
Dina Pal Subscriber

Posted on

How to Send Email in Node.js Using Nodemailer Package

Sending an email in Node.js requires an email server and a Node.js package for sending emails. One popular package for this is Nodemailer. Here's a basic example of how to send an email using Nodemailer in Node.js:

  1. First, install Nodemailer using npm:
    npm install nodemailer

  2. Next, require Nodemailer in your Node.js file:
    const nodemailer = require('nodemailer');

  3. Create a transport object using the SMTP protocol and your email provider's credentials. Here's an example using Gmail:

let transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: 'your-email@gmail.com',
        pass: 'your-email-password'
    }
});

Enter fullscreen mode Exit fullscreen mode
  1. Define the email message object, including the sender, recipient, subject, and message body:
let mailOptions = {
    from: 'your-email@gmail.com',
    to: 'recipient-email@example.com',
    subject: 'Test Email',
    text: 'This is a test email from Node.js'
};
Enter fullscreen mode Exit fullscreen mode
  1. Use the transporter.sendMail() method to send the email:
transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
        console.log(error);
    } else {
        console.log('Email sent: ' + info.response);
    }
});

Enter fullscreen mode Exit fullscreen mode

Note: You may need to allow access to less secure apps on your Gmail account. To do this, go to your Google Account settings, select Security, and turn on "Less secure app access".

Top comments (1)

Collapse
 
steve-lebleu profile image
Steve Lebleu

Thanks for sharing. You can now easily send SMTP transactional email using Cliam. It's a clear response to heterogeneous complexity of email sending. SMTP or API provider, same interface. If you switch the way you send emails, your code doesn't care.

There is the beast: github.com/steve-lebleu/cliam

With this package, you just need to define your configuration:

{
  "id": "hosting-smtp",
  "auth": {
    "username": "USERNAME",
    "password": "¨PASSWORD"
  },
  "options": {
    "host": "mail.host.com",
    "port": 587,
    "secure": true
  }
}
Enter fullscreen mode Exit fullscreen mode

And to shoot:

import { Cliam } from 'cliam';

const payload = {
  transporterId: 'hosting-smtp',
  meta: {...},
  content: [
    { type: 'text/html', value: '<html><p>Email content</p></html>' }
  ]
};

Cliam.mail('user.welcome', payload)
  .then(res => {
    console.log('Email has been delivered: ', res);
  })
  .catch(err => {
    console.log('Error while mail sending: ', err)
  });
Enter fullscreen mode Exit fullscreen mode

The nodemailer core library is still used for SMTP sendings.