首页 > 解决方案 > Nodemailer 附件不起作用

问题描述

我正在尝试使用 Nodemailer 发送带有电子邮件的附件,但附件出现“意外标识符”错误。似乎 nodejs 无法识别“附件”。除了nodemaler之外,我还需要从npm安装什么,下面的路径是电子邮件路由:

app.post("/send", function(req,res){

var transporter = nodemailer.createTransport({
 service: 'gmail',
 auth: {
        user: 'my gamil',
        pass: 'my gmail password'
    }
});


const mailOptions = {
  from: req.body.fr, // sender address
  to: req.body.to, // list of receivers
  bcc: req.body.fr,
  subject: req.body.subject, // Subject line
  html: '<h4>Dear ' + req.body.contname+ '</h4>' + '<p>'+ req.body.message + '</p>' + '<p>Kind Regards</p>' + req.body.user// html body
  attachments: [  
        {   
          filePath: req.body.myFile,
        },
        {   
          filename: req.body.myFile,
        },   
    ],
};

    transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
        return console.log(error);
    }
    console.log('Message sent: %s', info.messageId);
    console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));


   });
 });

标签: node.jsexpress

解决方案


如果你得到,这个:

        attachments: [{
        ^^^^^^^^^^^

SyntaxError: Unexpected identifier

这是因为您在html属性末尾缺少逗号。

const mailOptions = {
    from: req.body.fr, // sender address
    to: req.body.to, // list of receivers
    bcc: req.body.fr,
    subject: req.body.subject, // Subject line
    // Comma missing at the end of html =>
    html: '<h4>Dear ' + req.body.contname + '</h4>' + '<p>' + req.body.message + '</p>' + '<p>Kind Regards</p>' + req.body.user, // Comma missing here
    attachments: [{
        filePath: req.body.myFile
    } {
        filename: req.body.myFile
    }]
};

它与 nodemailer 附件不起作用无关。您的代码有语法错误。


推荐阅读