使用nodemailer从表单发送邮件

时间:2018-02-26 09:05:15

标签: node.js nodemailer

我刚开始使用node.js,并希望对nodemailer做一些事情。 我使用npm install (package name)

安装了软件包(Oauth2,Express,Body-parser,Node,Nodemailer)

我遇到的问题是当我尝试使用req.body.subject从我的HTML表单中获取信息时,它会给出错误,即它没有定义req。 (通过在cmd中执行node app.js发送邮件可以正常工作并且不会出现任何错误)

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>

我的电脑和服务器上出现此错误。 我一直在寻找答案,但是找不到我的问题的答案。 我很抱歉,如果我在这篇文章中做错了什么或者我不是很清楚我在这里很新。

代码:

HTML表单。

<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代码。

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

});

如果这个问题的答案非常简单易行,我很抱歉,这是我尝试使用nodemailer和node.js时的第一个真实内容。

3 个答案:

答案 0 :(得分: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');
    }
  });
});

答案 1 :(得分:0)

req实际上没有在你的代码中定义,我想你在点击按钮时发送电子邮件而不是在服务器启动时发送电子邮件,然后请求/send-email API发送电子邮件。

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

答案 2 :(得分:0)

我无法在您的代码中看到“/ send-email”POST api。你必须为它定义一个路由,就像在你的情况下/ send-email从HTML调用POST api一样,所以你应该在你的js文件中为它定义路由。然后,您可以访问app.post api实现中的 req 对象。 以下是示例代码。

    // 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");
});