使用 nodemailer 从表单发送邮件

Sending mail from a form using nodemailer

我刚开始使用 node.js,想用 nodemailer 做点什么。 我已经使用 npm install (package name)

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

我遇到的问题是,当我尝试使用 req.body.subject 从我的 HTML 表单中获取信息时,它给出了未定义请求的错误。 (通过在 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>

我的电脑和服务器上都出现了这个错误。 我一直在寻找答案一段时间,但找不到我的问题的答案。 如果我在此 post 中做错了什么或不够清楚,我很抱歉,我在这里很新。

代码:

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.

做的第一件真实的事情
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');
    }
  });
});

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

我看不到在您的代码中公开的“/send-email”POST api。您必须为其定义一条路线,因为在您的情况下 /send-email POST api 是从 HTML 调用的,因此您应该在您的.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");
});