2

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.

Xander
  • 33
  • 1
  • 10

3 Answers3

0
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');
});

app.post('/send-email', function (req, res) {
  console.log(req);       

  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');
    }
  });
});
аlex
  • 5,426
  • 1
  • 29
  • 38
0

req is really not defined in your code, and i guess that you what to send email when you click the button rather than send the email when server startup, then request the /send-email API to send the email.

        app.post('/send-email', function(req, res) {
            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');
                }
            });
        });
Cr.
  • 886
  • 7
  • 12
  • The only error I get now is `Cannot POST /send-email` could you explain to me what I am doing wrong? I can also give my updated code if you want. – Xander Feb 26 '18 at 10:49
  • What is `Cannot POST /send-email` means, can not request in browser or can not find the `/send-email` API? – Cr. Feb 27 '18 at 01:25
0

I cannot see the "/send-email" POST api exposed in your code. You have to define a route for the same, as in your case /send-email POST api is called from HTML, so you should have the route defined for it in your js file. Then you can access req object inside your app.post api implementation. Below is the sample code.

    // define a route that will send email
    app.post('/send-email', function(req, res) {

    //Here you can access req parameter
       var body  = req.body;
        //WRITE HERE ALL CODE THAT IS RESPONSIBLE FOR SENDING EMAIL
        //I am copying your above code of nodemailer that actually sends email, some correction may be required
        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');
        }

        });

});

// listen for all incoming requests
app.listen(3000, function(){
   console.log("Server is listening on port 3000");
});
Reena Upadhyay
  • 1,977
  • 20
  • 35