I just started out with node.js and wanted to do something with nodemailer.
I've installed the packages (Oauth2, Express, Body-parser, Node, Nodemailer) using npm install (package name)
The issues I have are when I try and get information from my HTML form by using req.body.subject
it gives the error that it req is not defined.
(Sending a mail by doing node app.js
in the cmd works fine and doesn't give any errors)
C:\Users\Gebruiker\Desktop\nodemailer\app.js:31
subject: req.body.subject,
^
ReferenceError: req is not defined
at Object.<anonymous> (C:\Users\Gebruiker\Desktop\nodemailer\app.js:31:14)
at Module._compile (module.js:660:30)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)
at Function.Module.runMain (module.js:701:10)
at startup (bootstrap_node.js:190:16)
at bootstrap_node.js:662:3
PS C:\Users\Gebruiker\Desktop\nodemailer>
I have this error on my pc and on my server. I have been searching for a answer for a while now and couldn't find a answer for my issue. I am sorry if I did something wrong in this post or that it isn't clear enough I am pretty new on here.
The code:
HTML form.
<html>
<head>
<script src="app.js"></script>
</head>
<form action="/send-email" method="post">
<ul class="inputs">
<li>
<label for="from">From</label>
<input type="text" id="from" name="from" />
</li>
<li>
<label for="to">To</label>
<input type="text" id="to" name="to" />
</li>
<li>
<label for="subject">Subject</label>
<input type="subject" id="subject" name="subject" />
</li>
<li>
<label for="message">Message</label>
<input type="message" id="message" name="message" />
</li>
<li>
<button>Send Request</button>
</li>
</ul>
</form>
</body>
</html>
Nodemailer code.
var nodemailer = require('nodemailer');
var path = require('path');
var bodyParser = require('body-parser');
var express = require('express');
var OAuth2 = require('oauth2');
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.get('/', function (req, res) {
res.render('default');
});
const transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
type: 'OAuth2',
user: 'xxxx@gmail.com',
clientId: 'xxxx',
clientSecret: 'xxxx',
refreshToken: 'xxxx',
accessToken: 'xxxx',
},
});
var mailOptions = {
from: 'Xander <xxxx@gmail.com>',
to: req.body.to,
subject: req.body.subject,
html: 'Hello Planet! <br />Embedded image: <img src="cid: download.jpg"/>',
attachments: [{
filename: 'download.jpg',
path: 'download.jpg',
cid: 'download.jpg'
}]
}
transporter.sendMail(mailOptions, function(err, res){
if(err){
console.log('Mail not sent');
} else {
console.log('Mail sent');
}
});
I am sorry if the answer to this question is really simple and easy, this is my first real thing I am trying to do with nodemailer and node.js.