【问题标题】:How to send pdf attachment with nodemailer?如何使用 nodemailer 发送 pdf 附件?
【发布时间】:2020-08-05 02:23:52
【问题描述】:

我有一个 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】:

    那是生成 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
     }
    })()
    

    希望对你有帮助。问候。

    【讨论】:

      猜你喜欢
      • 2016-03-30
      • 2022-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-30
      • 1970-01-01
      • 2023-03-19
      • 2020-09-03
      相关资源
      最近更新 更多