Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a content id image attachment for SendGrid in C#

I was unable to send email images, with Sendgird, to gmail using an inline/embedded method. Here is my SO thread covering this. So I tried adding a cid attachment, but I'm not sure if I'm adding it right because the image isn't being shown in the email but being sent as an attachment at the bottom of the email.

So how do I attach the image as a cid?

Here is my code.

In the email I have this

<img alt="SpaceImage" title="Space Image" style="display: block" width="225" height="126" src="cid:spacethumbnail" />

Then in my c# I have this.

Attachment attachment = new Attachment();
        attachment.ContentId = "spacethumbnail";
        attachment.Content = Convert.ToBase64String(newEvent.SpaceThumbnail);
        attachment.Type = "image/jpg";
        attachment.Disposition = "inline"; // fixed the issue
        attachment.Filename = "space-thumbnail.jpg";

and then I add this attachment to my send grid email like this

Mail mail = new Mail();
        mail.Subject = message.Subject;
        mail.From = new Email("[email protected]");
        mail.AddContent(new Content("text/HTML", message.Body));
        foreach(Attachment attachment in attachments)
        {
            mail.AddAttachment(attachment);
        }

        // add multiple recipients if needed
        Personalization personalization = new Personalization();
        foreach (string emailAddress in message.Destination.Split(','))
        {
            personalization.AddTo(new Email(emailAddress));
        }
        mail.AddPersonalization(personalization);

        dynamic response = sg.client.mail.send.post(requestBody: mail.Get());

How do I add the image as a cid attachment and not a regular attachment?

like image 459
user1186050 Avatar asked Sep 14 '25 21:09

user1186050


1 Answers

Since I don't like it when answers are in comments, for better visibility, I'm posting the answer from @user1186050 that seems to have solved the question.

In the C# file, adding: attachment.Disposition = "inline"; fixed the issue.

like image 91
anthonyjdella Avatar answered Sep 16 '25 10:09

anthonyjdella