如何在nodejs中将PDF文件作为附件发送?

时间:2017-08-21 07:19:52

标签: node.js

我正在尝试将PDF文件作为附件发送给用户,但在打开该文件错误时

“无法加载PDF文档。”

我正在使用节点邮件程序发送电子邮件。

我没有遇到问题。

请帮忙!

这是我的代码: -

router.get('/file',function(req, res){
    var fromName = "Ikshit";
    var mailOptions={
        to: 'userEmailId@gmail.com',
        subject: 'Test',
        from: "email@gmail.com",
        headers: {
            "X-Laziness-level": 1000,
            "charset" : 'UTF-8'
        },
        attachments: [
   
        {
            
            raw: 'Content-Type: application/pdf; charset=utf-8;\r\n' +
                 'Content-Disposition: attachment;filename=text.pdf;\r\n' +
                 '\r\n' +
                 'Hello world!'
        }
    ],
        html: 'Text'
       
    }
    var transporter = nodemailer.createTransport({
        service: 'Gmail',
        auth: {
            user: 'email@gmail.com', 
            pass: 'password' 
        }
    });
    transporter.sendMail(mailOptions, function(error, response){
        if(error){
           return res.send(err);
        }
        else{
            res.send({
                state:'success',
                message:"Send"
            });
        }
    });
})

2 个答案:

答案 0 :(得分:0)

试试这种方式......

var mailOptions = {
  from: 'foo@bar.com'.
  to: 'bar@foo.com',
  subject: 'an attached file',
  text: 'check out this attached pdf file',
  attachments: [{
    filename: '<fileName>',
    path: '<PDF file absolute path>'
    contentType: 'application/pdf'
  }]};

transporter.sendMail(mailOptions, function (err, info) {
     if(err){
       console.error(err);
       res.send(err);
     }
     else{
       console.log(info);
       res.send(info);
     }
  }
);

答案 1 :(得分:0)

试试这段代码,它肯定有效

fs.readFile("E:/syed/nodejs/tasks/mail/mailwithdb/sheet.pdf",function(err,data){
var mailOptions={
from:' <mail@gmail.com>',
to:'mail@gmail.com',
subject:'Sample mail',
text:'Hello !!!!!!!!!!!!!',
attachments:[
{
    'filename':'sheet.pdf',
     'content': data,
     'contentType':'application/pdf'
}]
}
transporter.sendMail(mailOptions,function(err,res){
if(err){
    console.log('Error');
}
else{
console.log('Email Sent');
}
})
});