Node.js和Nodemailer:我们可以将PDF文档附加到电子邮件中吗?

时间:2015-09-23 03:47:25

标签: javascript node.js email-attachments nodemailer

我想使用nodemailer和node.js附加PDF文档,但是,我找到的与nodemailer附件的唯一示例是.txt文件(here)。

有没有人知道nodemailer是否支持PDF文档附件?

最初看起来可以附加PDF,但通过电子邮件到达的PDF文件似乎已损坏(见图)。

enter image description here

代码:(改编自Mahesh的回答)

fs.readFile('/filePath/fileName.pdf', function (err, data) {
if (err) throw err;                                                  
var mailOptions = {
    from: 'Test <formEmail@gmail.com>', // sender address                                   
    to: 'toPersonName <toEmail@gmail.com>', // list of receivers                                 
    subject: 'Attachment', // Subject line                                                 
    text: 'Hello world attachment test', // plaintext body                                                 
    html: '<b>Hello world attachment test HTML</b>', // html body                                               
    attachments: [
        {
            filename: 'fileName.pdf',                                         
            contentType: 'application/pdf'
        }]
};

// send mail with defined transport object                                                 
transporter.sendMail(mailOptions, function(error, info){
    if(error){
        return console.log(error);
    }
    console.log('Message sent: ' + info.response);
});
console.log(data);
});

终端响应:

<Buffer 25 50 44 46 2d 31 2e 33 0a 25 c4 e5 f2 e5 eb a7 f3 a0 d0 c4 c6 0a 34 20 30 20 6f 62 6a 0a 3c 3c 20 2f 4c 65 6e 67 74 68 20 35 20 30 20 52 20 2f 46 69 ... >
Message sent: 250 2.0.0 OK 1443026036 hq8sm3016566pad.35 - gsmtp

4 个答案:

答案 0 :(得分:11)

是的,你可以。您必须添加要尝试附加的文件的路径。

transporter.sendMail({
  from: 'foo@bar.com',
  to: 'bar@foo.com',
  subject: 'An Attached File',
  text: 'Check out this attached pdf file',
  attachments: [{
    filename: 'file.pdf',
    path: 'C:/Users/Username/Desktop/somefile.pdf',
    contentType: 'application/pdf'
  }],
  function(err, info) {
    if (err) {
      console.error(err);
      res.send(err);
    } else {
      console.log(info);
      res.send(info);
    }
  }
});

答案 1 :(得分:1)

是的,您可以将pdf文档附加到电子邮件中,获取可以使用path的路径,然后从当前文件到您要附加的pdf。这对我有用。

// node-mailer.js
const nodemailer = require('nodemailer');
const path = require('path');
...
const mailOptions = {
    from: '',
    to: '',
    subject: '',
    text: '',
    html: '',
    attachments: [
        {
            filename: 'file-name.pdf', // <= Here: made sure file name match
            path: path.join(__dirname, '../output/file-name.pdf'), // <= Here
            contentType: 'application/pdf'
        }
    ]
};

transporter.sendMail(mailOptions, function(error, cb) {

});
  • 我的文件结构/树:
├── package-lock.json
├── package.json
├── output
│   └── file-name.pdf
├── routes
│   └── node-mailer.js <= Current file
└── server.js

希望这对某人有帮助:) 编码愉快!

答案 2 :(得分:0)

请记住两点。

  1. 提供pdf文件的完整地址。您可以使用__dirname(见下文)

  2. 文件名和路径上的pdf名称应完全相同。

    let info = await transporter.sendMail({
      from: '"Subject Foo Bar" <foo@bar.com>', // sender address
      to: `foo@bar.com, foofoo@bar.com`, // list of receivers
      subject: "Your's subject", // Subject line
      text: "Body of the email",
      attachments: [
        {
          filename: "Trial_Agreement.pdf",
          path: __dirname + "/Trial_Agreement.pdf",
        },
      ],
    });
    

答案 3 :(得分:0)

是的,很容易做到。我最近从事的项目需要类似的东西,对我来说很好。我使用Gmail在这里发送邮件。

导入Nodemailer

const nodemailer = require('nodemailer');

发送邮件的主要功能

const sendEmailWithPromiseWithDynamicData = async () => {        
    let mailOptions = mailOptionsForDynamicMail()
    return new Promise((resolve, reject) => {
    createEmailTranspoter().sendMail(mailOptions, async(error, info) => 
    {                      
        if (error) {
        reject(error);
    }
        resolve(info);
    });
  });
}

邮件选项功能

const mailOptionsForDynamicMail = async() => {            
            return {
                from: `"PROJECT NAME" <SENDER EMAIL ADDRESS>`, // sender address
                to: "RECEIVER EMAIL ADDRESS", // list of receivers
                subject: "Test Subject", // Subject line
                text: "Test Text", // plain text body
                html: generateEmailTemplateForDynamicMail(), // html body
                attachments: [
                    {   // utf-8 string as an attachment
                        filename: "YOUR ATTACHMENT FILE NAME", // file name, like 'test.pdf'
                        href: "LINK TO THE FILE" // link to the file, like http://example.com/invoices/test.pdf 
                    }
                ]
            };
        }
    }

创建邮件传输器

const createEmailTranspoter = () => {        
        return nodemailer.createTransport({
            host: 'smtp.gmail.com', //your smtp host name
            service: 'Gmail', // your service name
            port: 465,
            secure: true, // true for 465, false for other ports
            auth: {
                user: "SENDER MAIL",
                pass: "SENDER MAIL PASSWORD"
            },
            tls: {
                rejectUnauthorized: true
            }
        });
    
    }

邮件HTML正文

const generateEmailTemplateForDynamicMail = async() => {
            return `
      <h4>This is a test mail</h4>
      <h5>Testing for email Attachments</h5>
      <br>
      <br>
      <br>
      <p></p>
      <p>Thanks</p>
      <p>Test person</p>
      `;
}

Nodemailer文档链接: https://nodemailer.com/message/attachments/

谢谢