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;