Sometimes, we want to send emails in Node.js.
In this article, we’ll look at how to send emails in Node.js.
How to send emails in Node.js?
To send emails in Node.js, we can use the nodemailer
package.
To install it, we run
npm i nodemailer
Then we use it by writing
const mailer = require("nodemailer");
const smtpTransport = mailer.createTransport("SMTP", {
service: "Gmail",
auth: {
user: "[email protected]",
pass: "password"
}
});
const mail = {
from: "from <[email protected]>",
to: "[email protected]",
subject: "Send Email Using Node.js",
text: "Node.js",
html: "<b>Node.js</b>"
}
smtpTransport.sendMail(mail, (error, response) => {
if (error) {
console.log(error);
} else {
console.log(response.message);
}
smtpTransport.close();
});
we call mailer.createTransport
to create the smtpTransport
object that we use to log into our SMTP server.
Then we call smtpTransform.sendMail
to send our email with the data coming from the mail
object.
If there’s an error, then error
is set in the callback.
Otherwise, response
is set.
Finally, we log out of the SMTP server with smtpTransport.close
.
Conclusion
To send emails in Node.js, we can use the nodemailer
package.