簡體   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