Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
jemelyah opened this issue Sep 19, 2017 · 5 comments
Closed

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

jemelyah opened this issue Sep 19, 2017 · 5 comments

Comments

@jemelyah
Copy link

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()
@jmelendev
Copy link

Are you still looking for a solution to this? I just set one up here using nodemailer

@jmelendev
Copy link

jmelendev commented 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

@Gottwik
Copy link
Owner

Gottwik commented Oct 7, 2017

hey, @jmelendev, awesome work figuring this out.

@jemelyah I'll close this as I believe it was answered. Feel free to reopen if you have any more questions regarding this.

@sergejreznik
Copy link

sergejreznik commented Jul 28, 2018

Is there anything more to do? Can't get it working on my system.

I can submit the form, but getting an empty body response. Any Idea?

@pecata83
Copy link

pecata83 commented 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()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants