Thursday, September 30, 2021

NodeJS 34: Send email from NodeJS using nodemailer

 NodeJS 34: Send email from NodeJS using nodemailer


Reference blog - https://www.w3schools.com/nodejs/nodejs_email.asp






Sendmail.js

"use strict";
const nodemailer = require("nodemailer");

// async..await is not allowed in global scope, must use a wrapper
async function main() {
// Generate test SMTP service account from ethereal.email
// Only needed if you don't have a real mail account for testing
//let testAccount = await nodemailer.createTestAccount();

//If we get this error - 535-5.7.8 Username and Password not accepted. Learn more at\n535 5.7.8
//then we
//Need to turn on Less secure apps from this link - https://myaccount.google.com/lesssecureapps
console.log("Entered main method.............");
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: "pavan.******@gmail.com", // generated ethereal user
pass: "********", // generated ethereal password
},
});
console.log("Transporter object is ready.........");
// send mail with defined transport object
let info = await transporter.sendMail({
from: '"Test Mail" <foo@example.com>', // sender address
to: "pavankumar******@gmail.com", // list of receivers
subject: "Mail from NodeJS app ✔", // Subject line
text: "Mail from NodeJS app...?", // plain text body
html: "<b>Hello...</b>", // html body
});

console.log("Message sent: %s", info.messageId);
// Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>

// Preview only available when sending through an Ethereal account
console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
// Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
}

main().catch(console.error);







No comments:

Post a Comment