attach a generated pdf to a smtpjs mail in js

How to Attach a Generated PDF to an SMTPJS Mail in JS

If you want to send an email with a generated PDF file attached using SMTPJS in JS, then this is the right guide for you. Here, I am going to show you how to attach a PDF file to an email using SMTPJS with the help of some code snippets.

Step 1: Generate a PDF file using jsPDF

In order to attach a PDF file to an email, you first need to generate a PDF file using jsPDF. Here's how you can do it:

const doc = new jsPDF();
doc.text("Hello World!", 10, 10);"hello-world.pdf");

This will generate a PDF file named "hello-world.pdf" with the text "Hello World!" at position (10, 10).

Step 2: Prepare the Email

Next, you need to prepare the email that you want to send with the attached PDF file. Here's how you can do it:

    SecureToken: "your_secure_token",
    To: "[email protected]",
    From: "[email protected]",
    Subject: "Attachment Test",
    Body: "This is a test email.",
    Attachments: [
            name: "hello-world.pdf",
            data: "data:application/pdf;base64," + btoa(doc.output())
    message => console.log(message)

In the code above, we are using SMTPJS's Email.send() function to send the email. We are passing the recipient's email address, sender's email address, email subject, email body, and an array of attachments as parameters to the function.

The attachment is an object with two properties: name and data. The name property specifies the name of the attachment file, and the data property is the base64-encoded data of the PDF file.

Step 3: Send the Email

Finally, you need to send the email using SMTPJS. Here's how you can do it:

    // email configuration
    message => console.log(message)

That's it! You have successfully attached a PDF file to an email using SMTPJS in JS.


In this guide, we have learned how to attach a generated PDF file to an SMTPJS mail in JS. We used jsPDF to generate a PDF file, prepared the email with the attachment using SMTPJS's Email.send() function, and then sent the email.

This is just one way to achieve this. You can also use other libraries like pdfmake or jspdf-autotable to generate PDF files, or use other email services like SendGrid or Mailgun to send emails.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]