Search code examples
javascriptnode.jssmtpsendgrid

Embedded images in email with sendgrid


Trying to use an embedded image in my template but the email won't be sent. The path should be correct and I am getting no error. When I delete the image everything works fine and I am receiving the mail.

const mailController = {
sendAnswers: async(certificate) => {
    try {
        let pathToAttachment = `./documents/${certificate.company.name}/${certificate.company.name}_${certificate.company.selectedLanguage}.pdf`;
        let attachment = fs.readFileSync(pathToAttachment).toString("base64");

        let answerTemplate = {
            to: 'invoice@test.de',
            from: 'no-reply@test.de', // Use the email address or domain you verified above
            subject: 'Test',
            text: 'Test Test Test',
            html: `
                <img alt="test" src="cid:logo">
                <div style="margin: 20px 20%; padding: 24px; border: 1px solid rgba(0, 0, 0, 0.2); border-radius: 6px;"><h1 style="text-align: center">Thank You! ${certificate.company.name}</h1>
                <p style="text-align: center">Text<br>
                More Text
                More and More Text</p>
                </div>
            `,
            attachments: [
                {
                    content: attachment,
                    filename: `${certificate.company.name}_Answers.pdf`,
                    type: "application/pdf",
                    disposition: "attachment"
                },
                {
                    content: fs.readFileSync(`./assets/images/Changemaker-Siegel.png`, { encoding: 'base64'}),
                    filename: "Changemaker",
                    type: "image/png",
                    content_id: "logo",
                    disposition: "inline"
                }
            ]
        };

        await sgMail.send(answerTemplate);
      } catch (error) {
        console.error(error);
    
        if (error.response) {
          console.error(error.response.body)
        }
      }
}

}


Solution

  • The issue is that your logo attachment is not being sent as a base 64 string. You are reading the attachment as if its encoding is base 64, which is a different thing.

    So, you have:

                content: fs.readFileSync(`./assets/images/Changemaker-Siegel.png`, {
                  encoding: "base64",
                }),
    

    But you need:

                content: fs.readFileSync(`./assets/images/Changemaker-Siegel.png`).toString("base64"),