如何使用nodemailer发送pdf附件?

问题描述 投票:0回答:1

我有一个js文件包含html内容。

。js文件

const data = (data) => {
  return `<h1> This is my pdf data </h1>`
}
export default data 

这是我的nodemailer函数

import template from "js_file_path"
const body = template(data);
const mail = mailcomposer({
        from: "XXXX",
        to: "XXXX",
        subject: `Subject`,
        attachments: [
          {
            filename: "Receipt.pdf",
            content: body
          }
        ]
      });
      // mail.build()

但是这不起作用。谁能建议我这样做的方法?

javascript node.js email pdf nodemailer
1个回答
0
投票

是生成PDF文件的库吗?

从“ js_file_path”导入模板

如果不是这种情况,则应使用从传递给它的模板生成pdf的库。

例如:https://www.npmjs.com/package/pdfkit

代码示例:

import pdfGenerator from "pdgGeneratorLibrary"
import pdfTemplate from "pdfTemplate"
import nodemailer from "nodemailer"

(async () => {
 try {
    // build your template
    const pdfBufferedFile = await pdfGenerator(pdfTemplate);

    // set your transport
    const transporter = nodemailer.createTransport({ ...});

    // set your options
    const mailOptions = {
        from: "XXXX",
        to: "XXXX",
        subject: `Subject`,
        attachments: [{
            filename: "Receipt.pdf",
            contentType: 'application/pdf', // <- You also can specify type of the document
            content: pdfBufferedFile // <- Here comes the buffer of generated pdf file
        }]
    }

    // Finally, send the email
    await transporter.sendMail(mailOptions, function (error, info) {
        if (error) {
            console.log(error)
        } else {
            console.log(info)
        }
    });

 } catch (err) {
  // to do handle error
 }
})()

希望它对您有帮助。问候。

© www.soinside.com 2019 - 2024. All rights reserved.