Dhana Lakshmi
Dhana Lakshmi

Reputation: 413

Sending notification email using nodemailer in nodejs

I have application built using angularjs and nodejs where the admin has to get a mail about the details form the contact us from of the application

I am using nodemailer for it but i not able to figure out how to send the details entered by the user coming from the request in the mail body am getting has req.body.name but excepted is the name of the user(eg:sam)

var nodemailer = require('nodemailer');

var smtpTransport = nodemailer.createTransport("SMTP",{
  service: "Gmail",  // sets automatically host, port and connection security settings
  auth: {
    user: "[email protected]",
    pass: "*****"
  }
});

router.route('/sendmail')
  .post(function(req,res){
    console.log("!!!!!!!!!!!!!!!!1");
    console.log(req.body);
    smtpTransport.sendMail({  //email options
    from: "[email protected]", // sender address.  Must be the same as authenticated user if using Gmail.
    to: "[email protected]", // receiver
    subject: "UsersQuery", // subject
    ***html: "<b style='color: #006600'>UserQuery</b><p>name:req.body.name</p><p>name:req.body.email</p><p>name:req.body.message</p>"***
    }, function(error, response){  //callback
  if(error){
    console.log(error);
  }else{
    console.log("Message sent: " + response.message);
  }
  smtpTransport.close(); // shut down the connection pool, no more messages.  Comment this line out to continue sending emails.
});
    res.send("done");
  });

Upvotes: 2

Views: 2028

Answers (2)

michelem
michelem

Reputation: 14590

You have to put the variables outside the quotes and possibly change them:

html: '<b style="color: #006600">UserQuery</b><p>name:' + req.body.name + '</p><p>name:' + req.body.email + '</p><p>name:' + req.body.message + '</p>'

Use double quotes only for HTML attributes (style, class, id, etc...), use single quote for the rest.

Upvotes: 3

codecmd
codecmd

Reputation: 201

If you're using node 4.0 or higher you should try template strings instead; you use backtick character instead of single or double quotes. This allows for multiline strings without having to add "\n" and a + at the end of each line.

This is much easier to read, also more cool!

html: `<b style='color: #006600'>UserQuery</b>
       <p>name: ${req.body.name}</p>
       <p>email: ${req.body.email}</p>
       <p>message: ${req.body.message}</p>`

Upvotes: 3

Related Questions