Environment & Dependencies
- Nodemailer is a Node.JS npm module for sending emails. This has been the go to solution to most NodeJS developers for email delivery in their applications.
- Ensure you have NodeJS installed as a run environment.
Prerequisites
β’ Basic knowledge of JavaScript programming.
β’ Knowledge Node.JS
β’ A code editor such as VSCode
Getting started
Go to your project directory
- Create package.json file
npm init -y
- install dependencies
npm i nodemailer -s
- create entry file mailer file & mail-template
touch index.js mailer.js mail-template.js
Project Structure
NB: to use ES6 synthax import dependencies, set type: 'module' in the package.json file.
Implementation
Note: To understand how to navigate the nodemailer codebase and understand how it is implemented, I used askyourcode.
This will save you a lot of time looking for code snippets and implementations online.
mail.js
- In this file, you will first create your mail
transporter
object from nodemailer. This transporter object make use of the service you are will use for sending the emails, the host and most important an auth object. This object is basically your email id and email password
import nodemailer from "nodemailer";
// create reusable transporter object using the default SMTP transport
const transporter = nodemailer.createTransport({
service: "gmail",
host: "smtp.gmail.com",
port: 587,
secure: false,
auth: {
user: "MAILID@gmail.com",
pass: "YOUR PASSWORD",
},
});
- The next thing is to create a reusable
SEND_MAIL
function. This function should take two arguments, the mail details and a callback function to handle reponse.
/** create reusable sendmail function
@params {object} options - mail options (to, subject, text, html)
@params {function} callback - callback function to handle response
*/
const SENDMAIL = async (mailDetails, callback) => {
try {
const info = await transporter.sendMail(mailDetails)
callback(info);
} catch (error) {
console.log(error);
}
};
- Export this function to make it accessible by any file you want to issue the SEND_MAIL from.
export default SENDMAIL;
HTML TEMPLATE (mail-template.js)
In most applications, developers are required to send a styled email to meet the Application or company's theme. This can be done in sending mails through nodemailer. You will have to create your own styled HTML TEMPLATE. Below is a sample of template and how to use it
// an email template that can be used with Nodemailer to send emails
const HTML_TEMPLATE = (text) => {
return `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>NodeMailer Email Template</title>
<style>
.container {
width: 100%;
height: 100%;
padding: 20px;
background-color: #f4f4f4;
}
.email {
width: 80%;
margin: 0 auto;
background-color: #fff;
padding: 20px;
}
.email-header {
background-color: #333;
color: #fff;
padding: 20px;
text-align: center;
}
.email-body {
padding: 20px;
}
.email-footer {
background-color: #333;
color: #fff;
padding: 20px;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<div class="email">
<div class="email-header">
<h1>EMAIL HEADER</h1>
</div>
<div class="email-body">
<p>${text}</p>
</div>
<div class="email-footer">
<p>EMAIL FOOTER</p>
</div>
</div>
</div>
</body>
</html>
`;
}
export default HTML_TEMPLATE;
index.js
This is the entry file for sending the email. This can be any file you want to execute your SEND_MAIL command from.
Here, you provide the details of the mail to be sent and finally make use of the SEND_MAIL function from the mailer.js
file
- Sample email details and how to make use of the HTML Template created
import HTML_TEMPLATE from "./mail-template.js";
const message = "Hi there, you were emailed me through nodemailer"
const options = {
from: "TESTING <sender@gmail.com>", // sender address
to: "someone@gmail.com", // receiver email
subject: "Send email in Node.JS with Nodemailer using Gmail account", // Subject line
text: message
html: HTML_TEMPLATE(message),
}
NB: The html value can be simply the message
text variable if you don't want to use any template.
- Initiate the SEND_MAIL command using the
options
object created.
import SENDMAIL from "./mailer.js"
// send mail with defined transport object and mail options
SENDMAIL(options, (info) => {
console.log("Email sent successfully");
console.log("MESSAGE ID: ", info.messageId);
});
Success Output
Common Errors
One error commonly encountered in sending email with nodemailer using gmail is the Application-specific password required
error.
Error: Invalid login: 534-5.7.9 Application-specific password required. Learn more at
534 5.7.9 https://support.google.com/mail/?p=InvalidSecondFactor r27-20020a056402035b00b00459012e5145sm10361434edw.70 - gsmtp
at SMTPConnection._formatError (PATH\node_modules\nodemailer\lib\smtp-connection\index.js:790:19)
at SMTPConnection._actionAUTHComplete (PATH\node_modules\nodemailer\lib\smtp-connection\index.js:1542:34)
at SMTPConnection.<anonymous> (PATH\node_modules\nodemailer\lib\smtp-connection\index.js:546:26)
at SMTPConnection._processResponse (PATH\node_modules\nodemailer\lib\smtp-connection\index.js:953:20)
at SMTPConnection._onData (PATH\node_modules\nodemailer\lib\smtp-connection\index.js:755:14)
at TLSSocket.SMTPConnection._onSocketData (PATH\node_modules\nodemailer\lib\smtp-connection\index.js:193:44)
at TLSSocket.emit (node:events:526:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at TLSSocket.Readable.push (node:internal/streams/readable:228:10) {
code: 'EAUTH',
response: '534-5.7.9 Application-specific password required. Learn more at\n' +
'534 5.7.9 https://support.google.com/mail/?p=InvalidSecondFactor r27-20020a056402035b00b00459012e5145sm10361434edw.70 - gsmtp',
responseCode: 534,
command: 'AUTH PLAIN'
}
This error is due to a security layer google uses to protect your account. You are required to create an App Password to use in this instance.
How to fix this Error
- Login to your google account.
- From the sidebar, click on security
- Scroll down to Signing in with google
- Click on App Passwords to Generate a new App Password
This will generate a 16 character xxxx xxxx xxxx xxxx
app-password.
Finally, Replace your actual password in the mailer.js file with the generated password. (don't include the spaces).
This should fix the error!
Feel free to comment below if you encountered any error in implementing it. Let's help each other.
Conclusion
In this article, We only learnt how to implement sending email in NodeJS with nodemailer using Gmail Service
You can use askyourcode to explore the package codebase nodemailer for more ways to improve on the implementation on html templates.
If you find this content helpful, Please Like, comment and share. Follow us for more articles on NodeJS.
Top comments (22)
Not working internal style in html page
Really?
Let me see a snippet of your code
const welcomeEmailTemplate = (fullName) => {
return `
<!DOCTYPE html>
Social Space
<br>
@import url("<a href="https://fonts.googleapis.com/css2?family=Signika&display=swap%22" rel="nofollow">https://fonts.googleapis.com/css2?family=Signika&amp;display=swap&quot;</a>);</p>
<div class="highlight"><pre class="highlight plaintext"><code> :root {
--primary-color: #8344ff;
}
body {
margin: 0;
padding: 0;
font-family: "Signika", sans-serif;
}
h1 {
margin: 0;
color: var(--primary-color);
}
p {
margin: 0;
text-align: justify;
}
a {
text-decoration: none;
color: black;
}
a:hover {
color: var(--primary-color);
}
li::marker {
margin: 0;
}
img {
width: 100%;
max-height: 300px;
margin: 20px 0px;
}
.container {
padding: 25px;
border: 2px solid var(--primary-color);
border-radius: 15px;
}
</style>
</code></pre></div>
<p></head><br>
<body><br>
<div class="container"><br>
<h1>Your Space for Connecting and Sharing !</h1><br>
<br /><br>
<p>Hey, ${fullName} ππ»</p><br>
<img<br>
src="https://res.cloudinary.com/socialspace/image/upload/v1690739392/email-vectors/welcomeVector.svg"<br>
alt="welcome"<br>
/><br>
<p><br>
We are thrilled to extend a warm welcome to you as a new member of our<br>
ever-growing community at<br>
<a style="color: var(--primary-color)" href="">Social Space</a> !<br>
</p><br>
<br /><br>
<p><br>
Your decision to join Social Space brings us one step closer to building<br>
a vibrant online space where users like you can connect with friends,<br>
family, and like-minded individuals, sharing your thoughts, memories,<br>
and experiences with the world.<br>
</p><br>
<br /><br>
<p><br>
Here at Social Space, our mission is to create an inclusive environment<br>
that fosters meaningful interactions, celebrates diversity, and respects<br>
the privacy and security of all our users.<br>
</p><br>
<br /><br>
<p><br>
If you have any questions, concerns, or suggestions, please don't<br>
hesitate to reach out to our friendly support team at<br>
<a<br>
style="color: var(--primary-color)"<br>
href=""<br>
></a<br>
><br>
We're here to ensure that your experience on Social Space is as<br>
enjoyable as possible.<br>
</p><br>
<br /><br>
<p><br>
Once again, thank you for choosing <a style="color: var(--primary-color)" href="">Social Space</a>. We are genuinely<br>
excited to have you on board and cannot wait to see the positive impact<br>
you will make within our community.<br>
</p><br>
<br /><br>
<p>Best regards,</p><br>
<br /><br>
<p>The Social Space Team</p><br>
<li><a href="">Yogesh Zala</a></li><br>
<li><a href="">Hiren Prajapati</a></li><br>
</div><br>
</body><br>
</html><br>
`;<br>
};</p>
<p>module.exports = welcomeEmailTemplate;</p>
<p>async function sendWelcomeEmail(email, fullName) {<br>
const mailOptions = {<br>
from: <code>Social Space <${process.env.EMAIL}></code>,<br>
to: email,<br>
subject: "Welcome to Social Space ! ππ»",<br>
html: welcomeEmailTemplate(fullName),<br>
};</p>
<p>await sendEmail(mailOptions);<br>
}</p>
The welcomeEmailTemplate looks fine and sould work.
Perhaps the issue will be your implementation. What error do you get?
Send me a mail let's take a close look at itπ
Thank You for response!
error not show any but styling is not show when i have sent email to someone only show content without styling....
Oh I see.
Did you use thisππ
Yes, I have used!
support.google.com/mail/thread/476...
Please check the above Google support link! I think have you idea.
Okay sure
Very informative
Thank you
Am I crazy but this doesn't work without getting gmail api key?
This works fine without any API key.
How are you implementing it?
Thanks for the "Application-specific password required" error resolution
I am glad it helped
Hey, i'm using my actual emailId and emailPassword to send mails using nodemailer, with smpt.gmail.com as host, still i'm not able to send the mails and getting the error of false credentials. can anyone please explain me why i'm getting such error?
`const nodemailer = require("nodemailer");
require("dotenv").config();
const mailSender = async (email, title, body) => {
try{
// mail send krne ke liye transporter use hota h
let transporter = nodemailer.createTransport({
host: process.env.MAIL_HOST,
auth:{
user: process.env.MAIL_USER,
pass: process.env.MAIL_PASS,
}
});
// console.log(body);
// console.log(transporter);
}
module.exports = mailSender;`
above is my code snippet for mailSender
please can anyone tell me, where i'm doing it wrong?
You are not suppose to use your actual gmail password here.
Generate an APP password from your google account and use that instead
Bro my original mail is sent to the user. Not the 'from' one. Why is it so?
You original email is used for the SMTP config so it is what Gmail uses.
Is there any way to send an email via the from one?
You have to modify the password by going to the security section of gmail.