来自:field的nodemailer mail选项始终从smtpTrans auth对象中使用的电子邮件发送邮件

时间:2017-04-20 05:39:51

标签: node.js email smtp nodemailer

我正在使用nodemailer来处理联系表单和邮件。

但是当我尝试将req.body.email设置为from:email时,它只使用身份验证电子邮件。所以我收到的所有电子邮件都是:me@me.com到:me@me.com

而不是从:customer@them.com到:me@me.com

我很确定我做得对

var mailOpts, smtpTrans;

  //Setup Nodemailer transport, I chose gmail. Create an routerlication-specific password to avoid problems.
  smtpTrans = nodemailer.createTransport({
      service: 'Gmail',
      auth: {
        user: "me@me.com",
        pass: "hey"
      }
  });
  //Mail options
    console.log(req.body.email);
  mailOpts = {
      from: req.body.email, //grab form data from the request body object
      to: 'me@me.com',
      subject: 'Stockist interest form',
      text: "Welcome to the My Leisure Stockists application process, we'd love to have you on board"+"\n Email: "+req.body.email
  };

  smtpTrans.sendMail(mailOpts, function (error, response) {

      if (error) {
        res.sendStatus(500);
      } else {
        res.sendStatus(200);
      };

  });

1 个答案:

答案 0 :(得分:0)

首先,您需要诸如bodyparser之类的东西。由于2019年可以使用:

app.use(express.json());
app.use(express.urlencoded({extended: true}));

通常先使用快递:

const express = require('express');
const app = express();

另一件事是这是一个文本字段,因此您将其放在字符串中。与es6表示法一样,您可以使用:

`${req.body.email}`

所以你会得到这样的东西:

const express = require('express');
const app = express();

const nodemailer = require('nodemailer')

app.use(express.json());
app.use(express.urlencoded({extended: true}));

const smtpTrans = nodemailer.createTransport({
    service: 'Gmail',
    auth: {
      user: "me@me.com",
      pass: "hey"
    }
});

app.post('/send-email', function (req, res) {
  const mailOptions = {
    from: `${req.body.email}`, // Sender address
    to: 'me@me.com',         // List of recipients
    subject: 'Stockist interest form',
    text: "Welcome to the My Leisure Stockists application process, we'd love to have you on board"+"\n Email: "+req.body.email
  };

  smtpTrans.sendMail(mailOptions, function (error, info) {
    if (error) {
      return console.log(error);
    }
    console.log('Message sent: ' + info.response);
  });

  res.redirect("/index.html");
})