繁体   English   中英

如何使用 nodemailer 发送 pdf 附件?

[英]How to send pdf attachment with nodemailer?

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

.js 文件

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

这是我的nodemailer function

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 文件的库吗?

从“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
 }
})()

我希望它对你有帮助。 问候。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM