How to send embedded images with sendgrid emails?

Diogo Arenhart picture Diogo Arenhart · Apr 2, 2013 · Viewed 17.4k times · Source

I'm starting with SendGrid to send my e-mails, but I coudn't find how to embed images. Without using SendGrid I was using the following code to send e-mails with embedded images:

var mail = new System.Net.Mail.MailMessage();
mail.Subject = "Warning";
mail.From = "[email protected]";
mail.To.Add("[email protected]");
mail.IsBodyHtml = true;
mail.Body = "<html><body><a href='http://www.mywebsite.com' title='My Website'><img src='cid:my_image' alt='My Image' border='0' /></a><br /><h1>My E-mail Title</h1>E-mail content.</body></html>";
var av = AlternateView.CreateAlternateViewFromString(mail.Body, null, "text/html");
av.LinkedResources.Add(new LinkedResource(@"C:\my_image.png", "image/png"){ContentId="my_image"});
mail.AlternateViews.Add(av);
var smtp = new SmtpClient("smtp.test.com");
smtp.Credentials = new NetworkCredential("user", "pass");
smtp.Send(mail);

--- EDITED ---

Now I'm using the following code to send my e-mails (using SendGrid classes).

var message = SendGrid.GetInstance();
message.Subject = "Warning";
message.From = new MailAddress("[email protected]");
message.To = new MailAddress[] { new MailAddress("[email protected]") };
message.Html = "<html><body><a href='http://www.mywebsite.com' title='My Website'><img src='cid:my_image' alt='My Image' border='0' /></a><br /><h1>My E-mail Title</h1>E-mail content.</body></html>";
var transportSMTP = SMTP.GetInstance(new NetworkCredential("user", "pass"));
transportSMTP.Deliver(message);

What I need to know is how to embed and link my images inside the e-mail using its content id (CID).

Answer

phillihp picture phillihp · Jul 8, 2015

I juggled around this for a little bit too. The solution was to Attach the image first and then to Embed afterwards with the direct name of the file in the email.

var myMessage = new SendGridMessage();
myMessage.AddTo("[email protected]");
myMessage.From = "[email protected]";
myMessage.Subject ="Forgotten Password";
string body = @"<div><img src='cid:email_reset' alt='Email Reset Header' border='0' /></div>" +
              @"<p>Content...</p>";

string att = Request.PhysicalApplicationPath + @"Content\files\images\email_reset.jpg";
var attachment = new Attachment(att, new ContentType("image/jpeg"));
var linkedResource = new LinkedResource(att, new ContentType("image/jpeg"));
myMessage.AddAttachment(attachment.ContentStream, attachment.Name);
myMessage.EmbedImage(attachment.Name, "email_reset");

myMessage.Text = WebUtility.HtmlDecode(Regex.Replace(body, "<[^>]*(>|$)", string.Empty));
myMessage.Html = body;

// Authenticate and Send the email