DEV Community

Cover image for How to send emails using Gmail and NodeJS
Mohamed Ahmed
Mohamed Ahmed

Posted on

How to send emails using Gmail and NodeJS

In this artical we will learn How to send emails using Gmail and NodeJS

Nodemailer:
Nodemailer is licensed under MIT license. It provides an easy way to send email.

Sending emails is a common feature that is present in many applications. This feature is used to notify user about news, like a newsletter, about your product status when it’s facing to an issue, recovery password and so on.

Step 1: Installing the nodemailer.
$npm install nodemailer

Step 2: Connecting with the Gmail
const nodemailer = require('nodemailer')

// create reusable transporter object using the default SMTP transport

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

Step 3: Configure Gmail account to accept less secure apps
Our application is classified as insecure by Gmail. To bypass it we can configure our account to allow insecure apps to connect with our account. When this configuration is enabled all apps with username and password can connect to our account in Gmail and send emails.

To enable it you need to go to https://myaccount.google.com/ and select your Google Account. Then go to Security in the left sidebar and search by “Less secure app access”.

step 4: Definitely sending emails.
The transporter object has a method called sendMail() that is responsible to send emails effectively.

transporter.sendMail({ from: '"Your Name" youremail@gmail.com', // sender address to: "receiverone@gmail.com, receivertwo@outlook.com", // list of receivers subject: "Medium @edigleyssonsilva ✔", // Subject line text: "There is a new article. It's about sending emails, check it out!", // plain text body html: "There is a new article. It's about sending emails, check it out!", // html body }) .then(info => { console.log({info}); }) .catch(console.error);

Note that in the createTransport we only pass an attribute called service where we define it asgmail and the auth with our credentials.
In the sendMail() we pass all data about email. That’s all. Try to running this example again and see the result. If it works well, you’ll get something as showed below in your terminal.

{ info: { accepted: [ 'receiver@gmail.com' ], rejected: [], envelopeTime: 871, messageTime: 651, messageSize: 747, response: '250 2.0.0 OK 1615152446 m6sm5222884qtx.3 - gsmtp', envelope: { from: 'fromemail@gmail.com', to: [Array] }, messageId: '95e9c9a0-9c20-fcda-1873-7f16aec2b293@gmail.com' } }

Top comments (0)