Dark Knight
Dark Knight

Reputation: 1083

How to send pdf attachment with nodemailer?

I have a js file contains the html content.

.js file

const data = (data) => {
  return `<h1> This is my pdf data </h1>`
}
export default data 

This is my 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()

But this is not working. Can anyone suggest me the way to do this?

Upvotes: 1

Views: 4799

Answers (1)

Mykhaylo Gusak
Mykhaylo Gusak

Reputation: 116

Is that a library that generates a PDF file?

import template from "js_file_path"

If that is not the case, you should use a library that generates a pdf from the template you pass to it.

For example: https://www.npmjs.com/package/pdfkit

Code example:

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
 }
})()

I hope it helps you. Greetings.

Upvotes: 6

Related Questions