简体   繁体   中英

Generate dynamic pdf and send it as attachment in email in nodejs using nodemailer, pdfkit and mailgun

In my Nodejs app, I'm generating a dynamic PDF file using pdfkit. And I would like to send the file as an attachment to a receiver mail using mailgun. I am able to send the text message to the receiver, and also able to generate the PDF in my system and display it on my browser. However, the attachment file is missing at the receiver's end. What could be wrong?

 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;

As per the documentation the config can have an attachment parameter, however, in your code, you misspelled the word attachments rather that attachment.

Config should be


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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