【问题标题】:Generate dynamic pdf and send it as attachment in email in nodejs using nodemailer, pdfkit and mailgun使用 nodemailer、pdfkit 和 mailgun 生成动态 pdf 并在 nodejs 中作为电子邮件附件发送
【发布时间】:2020-09-20 13:01:51
【问题描述】:

在我的 Nodejs 应用程序中,我正在使用 pdfkit 生成一个动态 PDF 文件。我想使用 mailgun 将文件作为附件发送到接收者邮件。我能够将文本消息发送给接收者,还能够在我的系统中生成 PDF 并将其显示在我的浏览器上。但是,在接收端缺少附件文件。有什么问题?

 const fs = require("fs");
const path = require("path");
const dotenv = require("dotenv");
const PDFDocument = require("pdfkit");

dotenv.config({ path: "./config/config.env" });

const getPdf = (req, res, next) =>{

  const doc = new PDFDocument();
  const invoiceName = "invoice.pdf";
  const invoicePath = path.join("data", invoiceName);

  var filepath = doc.pipe(fs.createWriteStream(invoicePath));
  doc.pipe(res);
  doc.fontSize(25).text("Hello where is my attachment!", 100, 100);

    doc.end();
  
    var api_key = process.env.api_key;
    var domain = process.env.domain;
    var mailgun = require("mailgun-js")({ apiKey: api_key, domain: domain });
  
   
  
    var data = {
      from: process.env.from,
      to: process.env.to,
      subject: "Hello",
      text: "HELLO WORLD",
      attachments: filepath
    };
  
    mailgun.messages().send(data, function (error, body) {
      if (error) {
        console.log(error);
      } else {
        res.render("confirmation.ejs", {
          pageTitle: "Message Sent",
          messageSent: "Message has been sent succesfully",
        });
        
      }
    });
    
  
};

module.exports = getPdf;

【问题讨论】:

    标签: node.js email-attachments nodemailer mailgun pdfkit


    【解决方案1】:

    根据documentation,配置可以有一个附件参数,但是,在您的代码中,您拼错了附件而不是附件。

    配置应该是

    
        var data = {
          from: process.env.from,
          to: process.env.to,
          subject: "Hello",
          text: "HELLO WORLD",
          attachment: filepath
        };
    

    【讨论】:

    • 感谢您的回答。你是对的,它应该没有s。但即使在更正之后,代码似乎也不起作用。
    猜你喜欢
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    • 2016-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    相关资源
    最近更新 更多