question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. ItΒ collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Email form with nodemailer - how to get the routes working?

See original GitHub issue

I try to make a contact form in the front, that will send an email thru the nodemailer in the back - maybe someone has done thhis before and has a solution? Actually, my routes don’t work as expected, maybe I am doing something wrong?

 var local_app = function () {}

// * β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” * //
// * 	init
// *
// *	gets called upon starting enduro.js production server
// *	@param {express app} app - express app
// *	@return {nothing}
// * β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” * //
local_app.prototype.init = function (app) {
	// express app available here
	// don't forget these routes will be available on production server server (defaults to localhost:5000)//
    
    // app.get('/random', function (req, res) {
    //     enduro.api.temper.render('random', { random_number: Math.random() })
    //         .then((output) => {
    //             res.send(output)
    //         })
    // })

    var nodemailer = require('nodemailer');

    app.post('/sayHello', handleSayHello); // handle the route at yourdomain.com/sayHello

    function handleSayHello(req, res) {
        // Not the movie transporter!
        var transporter = nodemailer.createTransport({
            service: 'Gmail',
            auth: {
                user: 'example@gmail.com', // Your email id
                pass: 'password' // Your password
            }
        });

        var text = 'Hello world from \n\n' + req.body.name;

        var mailOptions = {
            from: 'example@gmail.com>', // sender address
            to: 'xyz@gmail.com', // list of receivers
            subject: 'Email Example', // Subject line
            text: text //, // plaintext body
            // html: '<b>Hello world βœ”</b>' // You can choose to send an HTML body instead
        };

        transporter.sendMail(mailOptions, function(error, info){
            if(error){
                console.log(error);
                res.json({yo: 'error'});
            }else{
                console.log('Message sent: ' + info.response);
                res.json({yo: info.response});
            };
        }); 
    }     
}

module.exports = new local_app()

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

3reactions
jmelendevcommented, Sep 26, 2017

I’ll just post my solution any way:

  const bodyParser = require('body-parser');
  const nodemailer = require('nodemailer');

  app.use(bodyParser.urlencoded({ extended: true }));

  app.post('/contact', function(req, res) {
    var body = req.body;
    var firstName = body.firstName;
    var lastName = body.lastName;
    var email = body.email;
    var message = body.message;

    var composedMessage = {
      text: 'Hey Person!\n\n' +
        `${firstName} ${lastName} has contacted you through your website. Here is their contact information and message: \n\n` +
        `First Name: ${firstName} \n` +
        `Last Name: ${lastName} \n` +
        `Email Address: ${email} \n` +
        `Message: ${message} \n\n`,
      subject: 'Website Inquiry'
    };

    var transporter = nodemailer.createTransport({
      host: '<email host>',
      port: <email port>,
      auth: {
        user: '<email address>',
        pass: process.env.email_key //this is a var stored in heroku, i dont recommend keeping a password string here
      }
    });

    transporter.sendMail({
      from: 'From Name <example@example.com>',
      to: '<email you'd like to send to>',
      subject: composedMessage.subject,
      text: composedMessage.text
    }, (error, info) => {
      if (error) {
        return console.log(error);
      } else {
        res.redirect('/contact');
      }
    });

  });

Here is the actual contact form:

<form class="contact-form" action="/contact" method="post">
    <div class="firstName field">
      <label for="first-name">First Name</label>
      <input type="text" name="firstName" value="" placeholder="">
    </div>

    <div class="lastName field">
      <label for="last-name">Last Name</label>
      <input type="text" name="lastName" value="" placeholder="">
    </div>

    <div class="email field">
      <label for="email">Email</label>
      <input type="email" name="email" value="" placeholder="">
    </div>

    <div class="message field">
      <label for="message">Message</label>
      <textarea name="message" rows="8"></textarea>
    </div>

    <div class="submit-button field">
      <button class="submit" type="submit">Submit</button>
    </div>

  </form>

Let me know if you have any questions

1reaction
pecata83commented, Jan 14, 2019

@sergejr to read the body you need to add app.use(bodyParser.json()); but this caused the Admin section to stop saving in save_cms so i had to use req.on(β€˜data’,… ,

below is my solution with basic Recaptcha integration.


// * β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” * //
// * 	/contact endpoint
// * β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” * //
const nodemailer = require('nodemailer')
const request = require('request')


let contact_endpoint = function () {}

// local dependencies

contact_endpoint.prototype.init = function (app) {
	
	// when adding bodyParser
	// app.use(bodyParser.urlencoded({ extended: true }))
	// app.use(bodyParser.json());

	app.post('/contact', function(req, res) {

		let jsonString = ''

		req.on('data', function (data) {
			jsonString += data
		})

		req.on('end', function () {

			jsonString = JSON.parse(jsonString)

			let body = jsonString;
			let name = body.fullName;
			let email = body.email;
			let message = body.message;
			let recaptcha = body.recaptcha;

			let transporterOptions = {
				//service: '', //if gmail need to enable less secure apps
				host: '',
				port: '',
				auth: {
					user: '',
					pass: process.env.email_key //this is a var stored in heroku, i dont recommend keeping a password string here
				},

                                //in case of rejectUnauthorized
				//tls:{ rejectUnauthorized: false }

			}

			let mailOptions = {

				from: transporterOptions.auth.user,
				to: email,
				subject: 'Website Inquiry',
				text: 'Hey Person!\n\n' +
					`Someone has contacted you through your website. Here is their contact information and message: \n\n` +
					`Name: ${name} \n` +
					`Email Address: ${email} \n` +
					`Message: ${message} \n\n`

			}

			let transporter = nodemailer.createTransport(transporterOptions)

			// not safe to keep your secret key  here should be in env.secretRecaptchaKey
			let secretKey = "";		

			if (recaptcha){

				// req.connection.remoteAddress will provide IP address of connected user.
				var verificationUrl = "https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey + "&response=" + recaptcha + "&remoteip=" + req.connection.remoteAddress;
				// Hitting GET request to the URL, Google will respond with success or error scenario.
				// 
				request(verificationUrl,function(error,response,body) {

					body = JSON.parse(body)

					if(body.success) {
						sendMail()
					}else{
						return res.json({success: false, reason : "Failed captcha verification"});
					}

				})

			}else{

				return res.json( { success: false } ) 

			}

			let sendMail = () => {

				transporter.sendMail(mailOptions, (error, info) => {

				    if (error) {

				      console.log(error)
				      res.json( { success: true } )

				    } else {

				      console.log(info)
				      res.json( { success: true } )

				    }
				})		
			}
		})
	})
}

module.exports = new contact_endpoint()
Read more comments on GitHub >

github_iconTop Results From Across the Web

Creating A Contact Form With JavaScript / Nodemailer
Hi Guys,Today we are going to be creating an email contact form using Nodemailer. I will be showing you how to set this...
Read more >
Coding a Contact Form with Next.js and Nodemailer - Medium
Last thing to do is to get it all working, right? Going back to the contact.js code, there are two final things we...
Read more >
How to Build a Contact Form with JavaScript and NodeMailer
Now all there's left to do is to set up the POST route to receive the submitted form data, parse it and send...
Read more >
Contact form with nodemailer in nodejs - Strapengine
In this tutorial, we will be looking at how we can create a contact form with a nodemailer using Gmail's SMTP server in...
Read more >
Sending Mail with Nodemailer in Node Application - Topcoder
Step 1. Setting up project: Β· Step 2. Configuring server.js and nodemailer Β· Step 3. Creating ejs form for mail. Β· Step 4....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found