Monday, 8 May 2017

Create dynamic html with ejs and node

I am trying to send dynamic mail to email IDs submitted using a form.
Below is my app.js code.

//Importing Packages
var express     = require('express');
var nodemailer  = require('nodemailer');
var bodyParser  = require('body-parser');


//Applying Express,Ejs to Node
app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:true}));
//Creating Nodemailer Transport
var transporter = nodemailer.createTransport({
    host: 'smtp.zoho.com',
    port: 465,
    secure: true,
    auth: {
        user: 'noreply@*****.com',
        pass: '******'
    }
});

//Root Route Setup
app.get('/', function(req, res){
    res.render("landing")
});

//Route to send the mail
app.post('/send', function(req,res){
    //Setting up Email settings
    var mailOptions = {
        from: 'noreply@*****.com',
        to : req.body.mail,
        subject: 'Verify Your Email',
        generateTextFromHtml : true,
        html: { path: './tmpl.html'}
    };

    //Execute this to send the mail
    transporter.sendMail(mailOptions, function(error, response){
        if(error) {
            console.log(error);
        } else {
            console.log(response);
        }
    });
    res.send("Mail succesfully sent!")
});

//Server &Port Settings
app.listen(3333, function(){
    console.log("Server is running...")
});

Below is my Form page code, which is an ejs file

<form action="/send" method="POST">
    <input type="email" name="mail" placeholder="Enter your email">
    <input type="text" name="name" placeholder="Enter your name">
    <input type="submit">
</form>

and below is my html template which is being mailed to the ID submitted using the form.

<html>
<body>

    <h1>Hello World!</h1>
    <a href="http://www.google/com">Link</a>

</body>
</html>

How do I read the Name from the form and then include that in the Email, so that in each email, I can address to that person using a variable, like "Hello Mr "

I am not able to figure out how to pass variable to the html file without emails blocking it as I am not able to use Javascript using Script tag inside the HTML file becuase almost all of the mail providers block JS in Email!

Can someone help me out with this please?



via Hisham Mubarak

No comments:

Post a Comment