简体   繁体   中英

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

}

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"),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM