Error: No recipients defined when trying to use nodemailer but recipient listed

Error: No recipients defined when trying to use nodemailer but recipient listed

我一直在尝试在我的 MEAN 应用程序上设置和使用 nodemailer。 这是 mail.js ...我用于我的 server.js 文件的路由。

'use strict';
const express = require('express');
const router = express.Router();
const nodemailer = require('nodemailer');
const config = require('./config');
const Message = require('../models/message');

var transporter = nodemailer.createTransport({
  service: 'gmail',
  secure: false,
  port: 25,
  auth: {
    user: config.mailUser, //same as from in mailOptions
    pass: config.mailPass
  },
  tls: {
    rejectUnauthorized: false
  }
});

router.post('/contact', function(req, res){
  var mailOptions = new Message({
    from: 'jon.corrin@gmail.com',
    to: req.body.to,
    subject: req.body.subject,
    text: req.body.text
    //html: req.body.html
  });

  transporter.sendMail(mailOptions, function(error, info){
    if(error){
      return console.log(error);
    }
    return console.log('Message %s sent: %s', info.messageId, info.response);
  });
});

module.exports = router;

我的 config.js 文件如下所示。

module.exports = {
  mailUser: 'jon.corrin@gmail.com',
  mailPass: 'XXXXXXXXX'
};

我正在使用邮递员对后端进行 API 调用,但结果是标题中所述的错误。有人知道为什么吗?似乎已经定义了收件人。

***更新

这是我的快捷应用

const express = require('express');
const cookieParser = require('cookie-parser');
const bodyParser = require("body-parser");
const mongoose = require('mongoose');

const appRoutes = require('./routes/app');
const keyRoutes = require('./routes/keys');
const mailRoutes = require('./routes/mail');

const app = express();
const uristring =
  process.env.MONGOLAB_URI ||
  process.env.MONGOHQ_URL ||
  'mongodb://localhost/db';


mongoose.connect(uristring, function (err, res) {
  if (err) {
    console.log ('ERROR connecting to: ' + uristring + '. ' + err);
  } else {
    console.log ('Succeeded connected to: ' + uristring);
  }
  });

app.use(express.static(__dirname + '/dist'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());

app.use(function (req,res,next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers','Origin, X-Requested-With, Content-Type, Accept');
  res.header('Access-Control-Allow-Methods', 'POST, GET, PATCH, DELETE, OPTIONS');
  next();

});

app.use('/mail', mailRoutes);
app.use('/keys', keyRoutes);
app.use('/', appRoutes);

//catch 404 and forward error handler
app.use(function (req, res, next) {
  return res.json('src/index');
});

app.listen(process.env.PORT || 8080);

module.exports = app;

这是我发送的请求

***更新

这是我的留言 class。

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const schema = new Schema({
  from: {type: String, required: true},
  to: {type: String, required: true},
  subject: {type: String, required: true},
  text: {type: String, required: true},
  html: {type: String, required: false}
});

module.exports = mongoose.model('Message', schema);

问题出在 mongoose Schema 上。我不是 mongoose 方面的专家,事实上我一生中从未使用过它,但在调试您的代码时,我发现了为什么您无法解决这个问题:

当您使用 console.log

打印此架构时
let mailOptions = new Message({
        from: 'jon.corrin@gmail.com',
        to: req.body.to,
        subject: req.body.subject,
        text: req.body.text
    //html: req.body.html
 });

它输出以下内容:

{ from: 'jon.corrin@gmail.com',
  to: 'some-email@gmail.com',
  subject: 'My subject',
  text: 'Email body',
  _id: 590135b96e08e624a3bd30d2 }

这看起来是一个普通的物体。事实上(不包括 _id 部分)它的输出与:

let mailOptions = {
    from: 'jon.corrin@gmail.com',
    to: req.body.to,
    subject: req.body.subject,
    text: req.body.text
    //html: req.body.html
};

但后者在将其传递给 nodemailer 时有效。

所以我想弄清楚 mailOptions 的真实身份(比如我是 JSON Bourne 什么的)

使用:

console.log(Object.assign({}, mailOptions));

我得到以下信息,这对 nodemailer 来说当然不好看。

{ '$__': 
   InternalCache {
     strictMode: true,
     selected: undefined,
     shardval: undefined,
     saveError: undefined,
     validationError: undefined,
     adhocPaths: undefined,
     removing: undefined,
     inserting: undefined,
     version: undefined,
     getters: {},
     _id: undefined,
     populate: undefined,
     populated: undefined,
     wasPopulated: false,
     scope: undefined,
     activePaths: StateMachine { paths: [Object], states: [Object], stateNames: [Object] },
     ownerDocument: undefined,
     fullPath: undefined,
     emitter: EventEmitter { domain: null, _events: {}, _eventsCount: 0, _maxListeners: 0 } },
  isNew: true,
  errors: undefined,
  _doc: 
   { _id: 590137d8f8c7152645180e04,
     text: 'Email body',
     subject: 'My subject',
     to: 'my-email@gmail.com',
     from: 'jon.corrin@gmail.com' } }

通读 mongoose 文档后,我找到了一种将其转换为简单 javascript 对象的方法,该对象可与 nodemailer 一起正常工作。该方法是:

toObject

综上所述,您有两个选择:

1) transporter.sendMail(mailOptions.toObject() //...如果你想使用猫鼬模式(我真的不知道为什么,但是......)

2) 删除 mongoose 模式并使用:(这是我推荐的方法,因为 mongoose 与 nodemailer 无关)

let mailOptions = {
    from: 'jon.corrin@gmail.com',
    to: req.body.to,
    subject: req.body.subject,
    text: req.body.text
    //html: req.body.html
 };

两个都测试了,我发送邮件没问题。