DEV Community

Cover image for Send mails using NodeJS
DrSimple
DrSimple

Posted on • Edited on

Send mails using NodeJS

Hey, fams! today we are going to learn how to send e-mails, right from our IDE using NodeJS. The module of interest is called Nodemailer.

puppy

Prerequisites

๐Ÿ”— NodeJs
๐Ÿ”— Nodemailer
๐Ÿ”— Email account


๐ŸŽฏ Steps
Open editor (VSCode ๐Ÿ˜), initialize your project with the command below

npm init -y 
Enter fullscreen mode Exit fullscreen mode

This command initiates a package.json, package.json.lock, and index.js (main entry file). The index.js will house all our logic.

Dependencies

๐Ÿ“ŒInstall Nodemailer

npm i nodemailer
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“Œ Import the package inside index.js

const nodemailer = require('nodemailer');
Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘จ๐Ÿฝโ€๐Ÿซ For security reasons, make sure you install and use dot.env package to prevent your password from being exposed or pushed to GitHub.
Install dotenv

npm i dotenv -S
Enter fullscreen mode Exit fullscreen mode

ignor

Require dotenv in your index.js file. I didn't require it in this project because I am using dummy data.

require('dotenv').config();
Enter fullscreen mode Exit fullscreen mode

Then, create a .env file your email and password

Email= ***********@gmail.com
Password= ******
Enter fullscreen mode Exit fullscreen mode

env


Logic

๐ŸŽฏ Your auth logic in index.js with dotenv

// Gmail account info
const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: process.env.EMAIL,
        pass: process.env.PASSWORD
    }
});
Enter fullscreen mode Exit fullscreen mode

๐ŸŽฏ Your auth logic in index.js without dotenv. Write the logic below and of course change the email to your own and the password to yours too.

// Gmail account info
const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: 'dsimple@gmail.com',
        pass: 'ilovemymama'
    }
});
Enter fullscreen mode Exit fullscreen mode

๐ŸŽฏ Next use the mailOption to send your message.

// Email info
const mailOptions = {
    from: 'dsimple@gmail.com',
    to: 'fams@gmail.com',
    subject: 'How to send emails using NodeJS',
    text: 'Follow the instructions and you will be fine'
};
Enter fullscreen mode Exit fullscreen mode

๐ŸŽฏ Lastly, write:

// Send email ๐Ÿ“ง  and retrieve server response
transporter.sendMail(mailOptions, function(error, info) {
    if (error) {
        console.log(error);
    } else {
        console.log('Email sent: ' + info.response);
    }
});
Enter fullscreen mode Exit fullscreen mode

When done properly, you should have the following logic in your index.js. That is if you choose not to use the dotenv
carbon (28)

To run: type ๐Ÿ‘‡๐Ÿผ in your terminal

node index
Enter fullscreen mode Exit fullscreen mode

Note: On your Gmail, do not forget to accept and allow the "Less secure apps" access to use your scripts with your Gmail SMTP connection. Gmail will alert you with an error if this option is off, you need to turn it on.
alert

Disable Less App Here

Multiple emails, CC and BCC

const mailOptions = {
    from: 'dsimple@gmail.com',
    to: 'fams@gmail.com,myrealfams@gmail.com',
    cc: 'lexus@gmail.com',
    bcc: 'sugar@gmail.com',
    subject: 'How to send emails using NodeJS',
    text: 'Follow the instructions and you will be fine'
};
Enter fullscreen mode Exit fullscreen mode

Send attachment

const mailOptions = {
    from: 'dsimple@gmail.com',
    to: 'fams@gmail.com,myrealfams@gmail.com',
    cc: 'lexus@gmail.com',
    bcc: 'sugar@gmail.com',
    subject: 'How to send emails using NodeJS',
    text: 'Follow the instructions and you will be fine',
    attachments: [{
    filename: "robocop.jpg", path: "./img/robocop.jpg"}]
};
Enter fullscreen mode Exit fullscreen mode

Thanks ๐Ÿ™Œ๐Ÿฝ for reading
Read my Web Socket

GitHub logo drsimplegraffiti / drsimplegraffiti

Config files for my GitHub profile.

Calm Developer

Hi ๐Ÿ‘‹, I'm Abayomi.

A Software Engineer interested in Backend

Software Engineer

A

drsimplegraffiti

drsimplegraffiti

drsimplegraffi1

Languages and Tools:

aws bash docker express javascript linux mongodb mysql nginx nodejs postgresql rabbitMQ redis typescript

drsimplegraffiti

ย drsimplegraffiti

drsimplegraffiti

Dev.to Post

๐Ÿ”— Improve your Github Profile

๐Ÿ”— Download Browser Page as PDF

๐Ÿ”— Send mails using NodeJS

๐Ÿ”— Chat App using Socket.io

๐Ÿ”— Expose a local web server to the internet

๐Ÿ”— Web scraping using Node Js

๐Ÿ”— Bash Terminal Guide

๐Ÿ”— Best Practices: Node JS Security

๐Ÿ”— Postman Hacks

๐Ÿ”— Time Zone: Nodejs

๐Ÿ”— Conditional Rendering : REACT





Discuss

What other email ๐Ÿ“ฌ services can you use apart from Gmail without toggling off the Less Secure App setting?

Reference

Download NodeJs
npm Reference
Nodemailer site

Latest comments (20)

Collapse
 
silentashish profile image
Ashish Gautam

Your mail will ended up in spam if you use google smtp.

Collapse
 
suchitra_13 profile image
Suchitra

Thank you so much.
But I am facing difficulty in attachment sending part, I have tried 3 times but couldn't send only text sent!

Collapse
 
jlong4223 profile image
Jared Long

@Suchitra try adding an 's' to attachment: attachments: [{

I ran into the same thing with just text showing up and checked the nodemailer documentation on attachements. That little mispelling fix should do the trick.

Also, if you want to learn how to do this with a React frontend and Google OAuth2, check out my nodemailer article as well :)

Collapse
 
suchitra_13 profile image
Suchitra

Thank you so much
It's working fine now:)

Collapse
 
drsimplegraffiti profile image
DrSimple

@Suchitra

Do you have a folder where your image is stored?

Example:

attachment: [{
filename: "robocop.jpg", path: "./img/robocop.jpg"}]
};

Collapse
 
suchitra_13 profile image
Suchitra

I kept image file in same folder where my index.js is present.
So in this case I just wrote:

attachment: [{
filename: "robocop.jpg", path: "robocop.jpg"}]
};

But it is not working:(

Thread Thread
 
horomancer profile image
horomancer

shouldn't it be

path: "./robocop.jpg"
Enter fullscreen mode Exit fullscreen mode
Collapse
 
leandrodiascarvalho profile image
leandro dias de carvalho

Parabens pelo conteรบdo.

Collapse
 
drsimplegraffiti profile image
DrSimple

obrigado muito apreciado

Collapse
 
drsimplegraffiti profile image
DrSimple

@mvoloskov Thanks for the contribution. It's always safety first.

Collapse
 
mvoloskov profile image
Miloslav ๐Ÿณ๏ธโ€๐ŸŒˆ ๐Ÿฆ‹ Voloskov

Kudos for teaching dotenv at the very beginning! I often see people pushing sensitive data into a public repo just because they treated environment security as an afterthought.

Collapse
 
drsimplegraffiti profile image
DrSimple

@njokdan You are welcome ๐Ÿ˜Š

Collapse
 
njokudanielo profile image
NJOKU DANIEL • Edited

Good content...Thanks

Collapse
 
drsimplegraffiti profile image
DrSimple
Collapse
 
brandonwallace profile image
brandon_wallace

Nice article! Thanks for posting it.

Collapse
 
drsimplegraffiti profile image
DrSimple

@salarc123 ... Thanks for the compliment. I will write as requested.