无法在节点中将邮件发送为UnhandledPromiseRejectionWarning错误

时间:2019-01-16 06:37:25

标签: node.js

发送邮件时出错:

(node:11928) UnhandledPromiseRejectionWarning: Error: Invalid login: 535 Authentication Failed

我尝试了nodemailer:

 //library.js 
const nodemailer = require("nodemailer"); 
module.exports
 = { 
transport:function(){     
let transporter = nodemailer.createTransport({
     host: "smtp.***.email",
     port: 587,
     secure: false, 
     auth: {
       user: ****, 
       pass: **** 
     }   
}); 
return transporter; 
}     

 //controller.js 
exports.sendemail = (require,res) => {   
let mailOptions =
 {
     from: '"Fred Foo " <foo@example.com>', 
     to: "baz@example.com", 
     subject: "Hello ✔", 
     text: "Hello world?",
     html: "<b>Hello world?</b>"  
}; 
transporter = transport.transporter();     
let info =  transporter.sendMail(mailOptions)     
console.log("Message sent: %s", info.messageId);    
}
  

消息已发送:       b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com

2 个答案:

答案 0 :(得分:3)

use same email at transporter and from on mail-options.
     //library.js 
    const nodemailer = require("nodemailer"); 
    module.exports = { 
    transport:function(){     
    let transporter = nodemailer.createTransport(
        {
         host: "smtp.***.email",
         port: 587,
         secure: false, 
         auth: {
           user: 'foo@example.com', 
           pass: **** 
         }   
    }); 
    return transporter; }}    

     //controller.js 
    exports.sendemail = (require,res) => {   
    let mailOptions =
     {
         from: '"Fred Foo " <foo@example.com>', 
         to: "baz@example.com", 
         subject: "Hello ✔", 
         text: "Hello world?",
         html: "<b>Hello world?</b>"  
    }; 
    transporter = transport.transporter();     
    transporter.sendMail(mailOptions).then((info) => 
    {
    console.log(info);
    return true;  
    }.catch(err => 
    {
      console.log("Error:", err);
       return false;
     });}

答案 1 :(得分:0)

发送邮件是异步过程。该警告表示存在被拒绝的未兑现承诺。来自the documentation的示例粘贴了错误的方式,省略了awaitsendMail返回一个需要链接的承诺:

transporter.sendMail(mailOptions)
.then(info => {
  // success response
})
.catch(err => {
  // error response
});