简体   繁体   English

使用nodemailer从表单发送邮件

[英]Sending mail from a form using nodemailer

I just started out with node.js and wanted to do something with nodemailer. 我刚开始使用node.js并想使用nodemailer做一些事情。 I've installed the packages (Oauth2, Express, Body-parser, Node, Nodemailer) using npm install (package name) 我已经使用npm install (package name)安装了软件包(Oauth2,Express,Body-parser,Node,Nodemailer 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. 我遇到的问题是,当我尝试使用req.body.subject从HTML表单中获取信息时,它给出了未定义req的错误。 (Sending a mail by doing node app.js in the cmd works fine and doesn't give any errors) (通过在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>

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表单。

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

});

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. 很抱歉,如果这个问题的答案真的很简单,这是我尝试使用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 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. 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');
                }
            });
        });

I cannot see the "/send-email" POST api exposed in your code. 我看不到您的代码中公开的“ / send-email” POST API。 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. 您必须为此定义一个路由,就像从HTML调用/ send-email POST api一样,因此您应该在js文件中为其定义路由。 Then you can access req object inside your app.post api implementation. 然后,您可以在app.post api实现中访问req对象。 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");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM