使用 sendgrid 在电子邮件中嵌入图像

Embedded images in email with sendgrid

尝试在我的模板中使用嵌入图像,但无法发送电子邮件。路径应该是正确的,我没有收到任何错误。当我删除图片时一切正常,我正在收到邮件。

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

}

问题是您的徽标附件未作为 base 64 字符串发送。您正在阅读附件,好像它的编码是 base 64,这是另一回事。

所以,你有:

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

但是你需要:

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