Nodemailer 附件为空

Nodemailer attachments are empty

我正在尝试将一些文件附加到我通过 NodeMailer 发送的电子邮件中。检查已发送的电子邮件,附件为空(即 0 字节)。如果我下载附件,我最终得到的是空文本文件。我错过了什么?

这是我的代码:

 const nodemailer = require('nodemailer')

 const lessSecureAuth = {
  user: "sender@email.com",
  pass: "password123"
 }
 const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: lessSecureAuth
 });

 const mailOptions = {
      from: 'sender@email.com',
      to: 'recipient@email.com',
      subject: 'Email Subject',
      html: `
          <h3>Hello World!</h3>
          <p>
              the quick brown fox jumps over the lazy dog
          </p>
      `,
      attachments: [
        {
          filename: 'attachFileTest.docx',
          filePath: '../uploads/attachFileTest.docx',
          contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        },
        {
          filename: 'attachFileTest.pdf',
          filePath: '../uploads/attachFileTest.pdf',
          contentType: 'application/pdf'
        },
        {
          filename: 'attachImageTest.png',
          filePath: '../uploads/attachImageTest.png',
          contentType: 'image/png'
        }
      ]
  };

  transporter.sendMail(mailOptions, function(error, info){
    if (error) {
      console.log("[ ERR ]", error);
    } else {
      console.log('Email sent: ' + info.response);
    }
  });

NodeJS: v12.16.1

nodemailer: v6.6.0

编辑#1

根据@Apoorva Chikara 的建议

您需要删除 Header - Content-Type,这就是它导致问题的原因。您也可以尝试像这样的示例附件并检查它是否有效:

attachments: [
        {
          filename: 'attachFileTest.docx',
          filePath: '../uploads/attachFileTest.docx',
          //contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        },
        {
          filename: 'attachFileTest.pdf',
          filePath: '../uploads/attachFileTest.pdf',
          //contentType: 'application/pdf'
        },
        {
          filename: 'attachImageTest.png',
          filePath: '../uploads/attachImageTest.png',
         // contentType: 'image/png'
        },
        {   // utf-8 string as an attachment. add this and check
            filename: 'text1.txt',
            content: 'hello world!'
        }
      ]  

在对文档和其他 Whosebug 帖子进行一些挖掘之后,我找到了答案:

使用绝对路径而不是相对路径到要附加的文件,同时使用attachment.path 属性 而不是 attachment.filePath 属性 成功了。

基本上,改变这个:

 {
   filename: 'attachFileTest.pdf',
   filePath: '../uploads/attachFileTest.pdf',
   contentType: 'application/pdf'
 },

到这个:

 {
  path: __dirname + '/../uploads/attachFileTest.pdf' // string concatination
  // path: `${__dirname}/../uploads/attachFileTest.pdf` // or string interpolation (ES6)
 }

在这种情况下 attachment.filenameattachment.contentType 都是不必要的,因为根据 docs:

{ // filename and content type is derived from path
  path: '/path/to/file.txt'
}