How to send PDF file with Mailgun in NodeJS (TS Format)?

131 views Asked by At

I'm using Mailgun to send customers invoices/receipts of their purchases, but I'm having problems with attaching the PDF created by MicroInvoice (which is based on PDFKit)

Since using Mailgun attachments require multipart/form-data encoding, I have tried to convert the PDF into that format.

const files = ["attachment", ["test", pdf.read()]];

But that results into the following error

"TypeError: Cannot read properties of undefined (reading 'name') at FormData._getContentType (/workspace/node_modules/form-data/lib/form_data.js:250:29) at FormData._multiPartHeader (/workspace/node_modules/form-data/lib/form_data.js:179:26) at FormData.append (/workspace/node_modules/form-data/lib/form_data.js:71:21) at i (/workspace/node_modules/mailgun.js/mailgun.node.js:2:33205) at e.addFilesToFD (/workspace/node_modules/mailgun.js/mailgun.node.js:2:33297)"

My current code is as follows

    const pdf = await myInvoice.generate();

    functions.logger.info("pdf1", pdf); //returns <ref *1> PDFDocument {***}
    functions.logger.info("pdf2", pdf.read()); //returns <Buffer 25 50 44.... 15758 more bytes>
    functions.logger.info("test", typeof pdf.read()); //returns object

    const files = ["attachment", ["test", pdf.read()]];

    const mg = mailgun.client({
      username: "api",
      key: "KEY",
      url: "https://api.eu.mailgun.net",
    });

    mg.messages
      .create("URL", {
        from: "FROM",
        to: "TO",
        subject: "Hello",
        text: "Testing some Mailgun awesomness!",
        attachment: files,
      })
      .then((msg) => functions.logger.log(msg)) // logs response data
      .catch((err) => functions.logger.log(err)); // logs any error`;
0

There are 0 answers