const express = require("express");
const mailer = require("nodemailer");
const app = express();
// Parse JSON bodies (as sent by API clients)
app.use(express.json());
// Parse URL-encoded bodies (as sent by HTML forms)
app.use(express.urlencoded({ extended: true }));
// Parse "multipart/form-data" using multer
//using mailgun to send email via nodemailer
const transport = mailer.createTransport({
host: "smtp.mailgun.org",
port: 587,
auth: {
user: "postmaster@sandbox85d0bb013570440e8cdc63cfe4475231.mailgun.org",
pass: "d6f92a983e92becc750b16cd1576791c-523596d9-9209e030",
},
});
app.post("/insert", async function (req, res) {
try {
console.log(req.body);
var mailOptions = {
from: req.body.mail_from,
to: req.body.mail_to,
subject: "Sending Email using Node.js",
text: "That was easy!",
html: "<b>Hello world ?</b>",
};
let mailSend = await new Promise((myResolve, myReject) => {
transport.sendMail(mailOptions, (error, info) => {
if (error) {
myReject(error);
} else {
myResolve("Email sent: " + info.response);
}
});
}).then((value)=>{
return value;
}).catch((err)=>{
return err;
});
res.status(200).send({ status: 200, mailSend: mailSend });
} catch (e) {
throw e;
}
});
app.get("/", function (req, res) {
res.send(`
<div style="margin:100px">
<form action="/insert" method="post">
<div class="form-group">
<input type="text" class="form-control-file" name="mail_from" placeholder="Enter Mail From">
<input type="text" class="form-control-file" name="mail_to" placeholder="Enter Mail To">
<input type="submit" value="Get me the stats!" class="btn btn-default">
</div>
</form>
</div>
`);
});
app.listen(3000, () => {
console.log(`App running at http://localhost:3000`);
});
- We are using nodemailer npm to send emails from Node.js
- We are using mailgun for transport mechanism
Comments
Post a Comment