Node Js Email send with template using nodemailer


 

const express = require("express");
const mailer = require("nodemailer");
const Email = require("email-templates");
const path = require("path");
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 path to join email template path
const templateDir = path.join(__dirname, "public", "email-template", "email");

//using mailgun transporter 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 {
    const email = new Email({
      message: {
        from: req.body.mail_from,
      },
      transport: {
        jsonTransport: true,
      },
      views: {
        root: templateDir,
        options: {
          extension: "hbs",
        },
      },
    });

    let locals = {
      name: "pradipta",
      attachment_file_name: "New Text Document.txt",
      attachment_file_url: attachment_file_url,
    };

    let getResponse = await email.render(templateDir, locals);

    var mailOptions = {
      from: req.body.mail_from,
      to: req.body.mail_to,
      subject: "Sending Email using Node.js",
      html: getResponse,
    };

    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`);
});
  1. We are using nodemailer npm to send emails from Node.js.
  2. We are using path npm to access and interact with the file system.
  3. We are using email-templates npm to Create, preview, and send custom email templates for Node.js.
  4. We are using handlebars npm view engine, which allow us to render web pages using template files. These templates are filled with actual data and served to the client. 
  5. We are using mailgun for transport mechanism.

email.hbs

<!DOCTYPE html>
<html>
<style>
input[type=text], select {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  display: inline-block;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}

input[type=submit] {
  width: 100%;
  background-color: #4CAF50;
  color: white;
  padding: 14px 20px;
  margin: 8px 0;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

input[type=submit]:hover {
  background-color: #45a049;
}

div {
  border-radius: 5px;
  background-color: #f2f2f2;
  padding: 20px;
}
</style>
<body style="width: 50%; margin-inline: auto; padding-top: 2%;" align="center">

<h3><a href="https://javascript-solving.blogspot.com/">Mail From javascript-solving </a></h3>

<div>
  <form action="#">
    <label for="fname">Mail From</label>
    <input type="text" id="fname" name="firstname" value="{{mail_from}}" readonly>

    <label for="lname">Mail To</label>
    <input type="text" id="lname" name="lastname" value="{{mail_to}}" readonly>

  </form>
</div>

</body>
</html>


Folder Structure

Comments

Post a Comment