Friday 19 October 2018

Using NodeMailer with Node JS Webpage

Hey everyone :)​I'm relatively new to js and I'm trying to learn by making a backend for a website. I currently have everything up and running through gulp and I am trying to add an email contact form using nodemailer.I've created a file called email.js which is stored with the rest of my js files and is then brought in with in my 'index.html' file, the form in the html uses the following header,
. When I submit the form however, it simply gives me an error of 'Cannot POST /contact'.How would you guys advise I try and fix this? Thanks for all help.​The code for the 'email.js' is as follows:const nodemailer = require('nodemailer'); const express = require('express'); const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.urlencoded({extended: true})); // POST route from contact form app.post('/contact', function (req, res) { let mailOpts, smtpTrans; smtpTrans = nodemailer.createTransport({ host: 'smtp.gmail.com', port: 465, secure: true, auth: { user: 'email', pass: 'psw' } }); mailOpts = { from: req.body.name + ' <' + req.body.email + '>', to: 'email', subject: 'New message from contact form', text: `${req.body.name} (${req.body.email}) says: ${req.body.message}` }; smtpTrans.sendMail(mailOpts, function (error, response) { if (error) { res.render('contact-failure'); } else { res.render('contact-success'); } }); });

Submitted October 19, 2018 at 01:49PM by magicthrowaway10199

No comments:

Post a Comment