Search code examples
javascriptnode.jspdfnodemailer

How to send a pdf save on s3 as attachment using Nodemailer


I have a function to send an email with a pdf attach, but when I try send a pdf that no has file locally, the email arrive without any attachment...

async sendEmailWithAtt(email, subject, message, pathAtt) {
    const transporter = nodemailer.createTransport({
        host: process.env.EMAIL_HOST,
        port: process.env.EMAIL_PORT,
        auth: {
            user: process.env.EMAIL_USERNAME,
            pass: process.env.EMAIL_PASSWORD
        },
        attachments: [
            {
                filename: 'Document',
                path: pathAtt, // URL of document save in the cloud.
                contentType: 'application/pdf'
            }
        ]
    });

    const mailOptions = {
        from: process.env.EMAIL_USERNAME,
        to: email,
        subject: subject,
        text: message
    };

    await transporter.sendMail(mailOptions);
}

Solution

  • Nodemailer documentation states that if you want to use an URL, you have to use href instead of path which is reserved for local files.

    If the file is not publicly available, you can pass some headers using httpHeaders property.

    attachments: [
     {
         filename: 'Document',
         href: pathAtt, // URL of document save in the cloud.
         contentType: 'application/pdf'
      }
    ]
    

    Aside from that, you're setting attachments in .createTransport you should put it inside the message instead.

    const mailOptions = {
        from: process.env.EMAIL_USERNAME,
        to: email,
        subject: subject,
        text: message,
        attachments: [ /* ... */]
    };
    
    await transporter.sendMail(mailOptions);