错误:尝试使用nodemailer但未列出收件人时未定义任何收件人

时间:2017-04-26 21:46:11

标签: javascript node.js mongoose nodemailer

我一直在尝试在我的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;

这是我发送的请求 enter image description here

enter image description here

***更新

这是我的留言课。

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

1 个答案:

答案 0 :(得分:1)

问题在于猫鼬Schema。我不是猫鼬的专家,实际上从来没有在我的生活中使用它,但在调试你的代码时,我发现为什么你有麻烦搞清楚:

使用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() //...如果您想使用mongoose架构(我真的不知道为什么,但是......)

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

测试了两者,我发送电子邮件没有问题。