I'm trying to embed an image in an email that's send with Sendgrid C# 9.28.1. But somehow the image is not displayed. There is also not a function anymore that's called EmbedImage. Is there a way to do this?
var client = new SendGridClient(_settings.ApiKey);
var myMessage = new SendGridMessage();
myMessage.AddTo(entity.Email);
myMessage.From = new EmailAddress(_settings.FromAddress, _settings.FromName);
myMessage.Subject = $"{_settings.FromName} - Image TEST";
var body = "<div style=\"width:200px;\"><img src=\"cid::IMAGE01\"/></div>"
@"<p>Test message?</p>";
var attachment = new SendGrid.Helpers.Mail.Attachment
{
ContentId = "IMAGE01",
Content = entity.Base64ImageString,
Type = "image/png",
Filename = "image.png"
};
myMessage.AddAttachment(attachment);
myMessage.HtmlContent = body;
await client.SendEmailAsync(myMessage);
CodePudding user response:
I was able to replicate your issue. When running your code I see the image attached, but not inlined into the body of the email.
To resolve the issue, I added the Disposition
property and set it to "inline"
.
message.AddAttachment(new Attachment
{
ContentId = "IMAGE01",
Content = Convert.ToBase64String(File.ReadAllBytes("image.png")),
Type = "image/png",
Filename = "image.png",
Disposition = "inline" // important!
});
Once I added the property, the image was displayed inline. (I also use a single :
instead of two :
in the HTML, so cid:
instead of cid::
but not sure it matters.
Here's what part of my email source looked like without the Disposition
property:
<html>
<body>
<img src=3D"cid:IMAGE01"/>
</body>
</html>
--d0e309773e8692891fcbf3a6dc18894582dea28d62adfe2bd8fd84a96b90
Content-Disposition: attachment; filename="image.png"
Content-Transfer-Encoding: base64
Content-Type: image/png; name="image.png"
Notice how IMAGE01
only appears in the HTML, but not in the attachment.
This is with the Disposition
property:
<html>
<body>
<img src=3D"cid:IMAGE01"/>
</body>
</html>
--5bb4b7a345af921dc9094ee0d66495c2a390a8aa6e89c2a41d96f8af8af5
Content-Disposition: inline; filename="image.png"
Content-ID: <IMAGE01>
Content-Transfer-Encoding: base64
Content-Type: image/png; name="image.png"
Notice how there's now a Content-ID: <IMAGE01>
parameter.
Having said that, there are also two alternatives, you can use a data URL to embed the base64 data into the HTML, or you can upload the image to the internet and reference it.
You can find the source code here: https://github.com/Swimburger/SendGridImages/blob/main/Program.cs