如何使用nodemailer发送pdf附件?

How to send pdf attachment with nodemailer?

我有一个 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()

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

那个是生成 PDF 文件的库吗?

import template from "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
 }
})()

希望对你有所帮助。你好。