Abhijeet
Abhijeet

Reputation: 316

Base64 encoded image sent using sendgrid not displayed in mails

I am trying to send a logo image in the HTML using sendGrid mailing service. I went through a lot of articles and tried a lot but still could not figure out on how to display inline image using content_id.

I went through following links but still could not make it work: [Link1][1]: https://sendgrid.com/blog/embedding-images-emails-facts/ [Link2][2]: https://github.com/sendgrid/sendgrid-nodejs/issues/841 Few of the answers suggest to add image as a base64 string in HTML but that does not work with few web mailing clients.

Here is my code: `

    try
    {

        const msg = {
            to: `${customerData.raw[0].invoicemail}`, // List of receivers email address
            from : '[email protected]',
            subject: `${subject}`, // Subject line
            html: emailData, // HTML body content
            attachments:
            [
            {filename:`${filename}`,content:invoice,type:"application/pdf"},
            {filename:'logo.jpg',content:logoImageData,content_id:'logo',type:"image/jpg",disposition:"inline"}
            ],
            }
            sgMail.send(msg)
            //return this.mailerService.sendEmail(msg)
    }
    catch
    {
        return false
    }`

And here is the HTML block:

<img src = "content_id:logo" alt = "Logo Image" width=140 height=20>

Also, the image is being received as an attachment but is not displayed.

Upvotes: 0

Views: 2692

Answers (1)

do-kevin
do-kevin

Reputation: 36

Sorry for the very late reply, I've also had trouble getting my image to display using SendGrid.

@Abhijeet, have you tried replacing src = "content_id:logo" with src="cid:logo"?

For other beginners, like myself, using SendGrid I will include the other steps that @Abhijeet already has done.

  1. Upload and convert your image file to base64 (we'll call this logoImageData).

  2. We want to replace the beginning of the base64 encoded image string using String.prototype.replace().

export const cleanLogoImageData = logoImageData.replace('data:image/jpeg;base64,' , '')
  1. Now, in the attachments for mail data for SendGrid, you need to add these to your object: filename, content, contentType, content_id, and disposition.
const msg = {
  attachments: [
    {
      filename: "logo.jpg",
      content: cleanLogoImageData,
      contentType: "image/jpeg",
      content_id: "logo",
      disposition: "inline",
    },
  ],
}

content_id and disposition: "inline" are what got my logo to show.

  1. Finally, in the html file holding your <img />, you must set the src as cid:logo or whatever your content_id is. And moreover, it's recommended to add align="top" and display: block in your img tag for better and consistent cross-platform email display of the image.
<img align="top"
     style="display: block"
     src="cid:logo"
     alt="company logo"
/>

Upvotes: 2

Related Questions