node.jsnodemailerhtml-pdf

NodeJS send a PDF by Email using pdf creator


I'm new with NodeJS. I'm trying to generate a PDF from HTML and send it by email using nodemailer.

exports.testReqID = async (req, res, next) => {
    const ID = req.params.myID;

    const htmlData = `
        <html>
            <head></head>
            <body>
                <h1>PDF Test. ID: ${ID}</h1>
            </body>
        </html>
    `; // Just a test HTML

    pdf.create(htmlData).toBuffer(function(err, buffer){
        let emailBody = "Test PDF";
        const email = new Email();
        const transporter = email.getTransporter();
        await transporter.sendMail({
            from: 'support@myemail.com', 
            to: 'me@myemail.com', 
            subject: "TEST", 
            html: emailBody, 
            attachments: {
                filename: 'test.pdf',
                contentType: 'application/pdf',   
                path: // How can I do it?
            }
        }); 
    });
};

The Email() class is just my settings for the nodemailer and it returns a transporter from transporter = nodemailer.createTransport(...)


Solution

  • You can send it as a buffer. docs

    exports.testReqID = async (req, res, next) => {
        const ID = req.params.myID;
    
        const htmlData = `
            <html>
                <head></head>
                <body>
                    <h1>PDF Test. ID: ${ID}</h1>
                </body>
            </html>
        `; // Just a test HTML
    
        pdf.create(htmlData).toBuffer(function(err, buffer){
            let emailBody = "Test PDF";
            const email = new Email();
            const transporter = email.getTransporter();
            await transporter.sendMail({
                from: 'support@myemail.com', 
                to: 'me@myemail.com', 
                subject: "TEST", 
                html: emailBody, 
                attachments: {
                    filename: 'test.pdf',
                    content: buffer',   
                }
            }); 
        });
    };