There are
two famous methods for sending mail. I’ll discuss both of them.
1. Sending mails using sendgrid (v3)
First, create
the free account in app.sendgrid.com
get the API
-> create new API
Register for
send authentication user-> to providing a mail for -> 'from' field
Settings
-> Sender Authentication -> Single Sender Verification -> Verify an
Address (or you will get an error of => error: The from address does not match a verified Sender
Identity.)
install sendGrid npm package
npm install --save sendgrid-v3-node
[official ->https://www.npmjs.com/package/sendgrid-v3-node]
const sendgrid = require("sendgrid-v3-node");
const mailOptions = {
sendgrid_key:
"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",
from_email: "kamalsilva007890@gmail.com
", //Single Sender
Verification Shoud be done
from_name: "KamalSilva",
to: "yasassandeepa007@gmail.com",
};
//inside the
controller we want to send mail ->
exports.sendmail = (req, res, next) => {
mailOptions.subject = "SendGrid Mail";
mailOptions.content =
"<strong>Testing
with sendgrid</strong><br></br><h1>Yasas
Sandeepa</h1>";
sendgrid
.send_via_sendgrid(mailOptions)
.then((response) => {
console.log(response);
})
.catch((err) => {
console.log("Errorr--------------");
console.log(err);
});
}
2. Sending a mail with fake SMTP
server
We are using
Mail trap here.
This is not
actually delivered the mail but you can see it in mailtrap mailbox.
First, create
an account and get the SMTP username and password settings in mailtrap.
Then install
nodemailer.
npm install --save nodemailer
const nodemailer = require("nodemailer");
exports.sendMail = (req, res, next) => {
let transport = nodemailer.createTransport({
host: "smtp.mailtrap.io",//no need to change
port: 2525,
auth: {
user: "e8bc95702fcb04", //get the username and
password in the mail box
pass: "9c416a31a224a8",
},
});
const message = {
from: "kamalSilva@gmail.com",
to: "yasassandeepa007@gmail.com",
subject: "Testing Mailtrap",
html: "<h1>Yooo
HOOO!!!!</h1><p>Get your <b>Tesla</b>
today!</p>",
};
transport.sendMail(message, function (err, info) {
if (err) {
console.log(err);
} else {
console.log(info);
}
});
res.render("auth/login", {
pageTitle: "Login Page",
active: "login",
errorMessage: req.flash("info"),
});
};

0 Comments