Javascript NodeEmailer附件为空
我正在尝试将一些文件附加到通过NodeMailer发送的电子邮件中。检查发送的电子邮件,附件为空(即0字节)。如果我下载附件,我最终会得到空文本文件。我错过了什么 这是我的代码:Javascript NodeEmailer附件为空,javascript,node.js,typescript,nodemailer,Javascript,Node.js,Typescript,Nodemailer,我正在尝试将一些文件附加到通过NodeMailer发送的电子邮件中。检查发送的电子邮件,附件为空(即0字节)。如果我下载附件,我最终会得到空文本文件。我错过了什么 这是我的代码: const nodemailer=require('nodemailer')) const lessecureauth={ 用户:“sender@email.com", 通行证:“密码123” } const transporter=nodemailer.createTransport({ 服务:“gmail”, au
const nodemailer=require('nodemailer'))
const lessecureauth={
用户:“sender@email.com",
通行证:“密码123”
}
const transporter=nodemailer.createTransport({
服务:“gmail”,
auth:lessecureauth
});
常量邮件选项={
发件人:'sender@email.com',
致:'recipient@email.com',
主题:'电子邮件主题',
html:`
你好,世界!
敏捷的棕色狐狸跳过了懒狗
`,
附件:[
{
文件名:“attachFileTest.docx”,
文件路径:'../uploads/attachFileTest.docx',
contentType:'application/vnd.openxmlformats of cedocument.wordprocessingml.document',
},
{
文件名:“attachFileTest.pdf”,
文件路径:'../uploads/attachFileTest.pdf',
contentType:'应用程序/pdf'
},
{
文件名:“attachImageTest.png”,
文件路径:'../uploads/attachImageTest.png',
contentType:'image/png'
}
]
};
transporter.sendMail(邮件选项,函数(错误,信息){
如果(错误){
日志(“[ERR]”,错误);
}否则{
console.log('发送的电子邮件:'+信息响应);
}
});
节点js:v12.16.1
nodeEmailer:v6.6.0
编辑#1
正如@Apoorva Chikara所建议的
您需要删除标题-内容类型,这就是它导致问题的原因。您也可以尝试这样的示例附件,并检查其是否有效:
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!'
}
]
在对文档和其他stackoverflow帖子进行了一些挖掘之后,我找到了答案: 对要附加的文件使用绝对路径而不是相对路径,同时使用
attachment.path
属性而不是attachment.filePath
属性就可以实现这一目的
基本上,改变这一点:
{
文件名:“attachFileTest.pdf”,
文件路径:'../uploads/attachFileTest.pdf',
contentType:'应用程序/pdf'
},
为此:
{
路径:_dirname+'/../uploads/attachFileTest.pdf'//字符串压缩
//路径:`${uuu dirname}/./uploads/attachFileTest.pdf`//或字符串插值(ES6)
}
在这种情况下,attachment.filename
和attachment.contentType
都是不必要的,因为根据:
它是否发送了尸体和其他细节?你能检查文件路径是否正确,文件是否存在吗?@ApoorvaChikara是的,它发送电子邮件正文和主题,文件存在于上载文件夹中。我建议你在选项中添加调试模式和记录器。选中删除
contentType
属性会产生相同的结果:空附件。添加文本文件附件只会导致附加文本文件。@kbien附加文本文件的原因是为了找出路径问题。如果可以看到路径中的数据,则文件未正确附加。这是由于路径。
{ // filename and content type is derived from path
path: '/path/to/file.txt'
}