.Net, HTML mails and embedded images
So recently I needed to take an image uploaded by the client and embed it into an email as part of a ‘send to a friend’ type piece of functionality. After much trial and error I managed to put all the pieces together – the tricky bit is taking an image that only lives in memory, attaching it to an email and then referencing that image from the html.
So here goes: (ImageData in the example method is the base64 encoded image data that was uploaded)
{
try
{
byte[] imageBytes = Base64DecodeString(ImageData);
MemoryStream memorystream = new MemoryStream(imageBytes);
memorystream.Seek(0, SeekOrigin.Begin);
System.Drawing.Image img = ByteArrayToImage(imageBytes);
MailMessage emailEnquiry = new MailMessage(ContactEmail, FriendEmail);
emailEnquiry.Subject = "here’s a gripping email";
emailEnquiry.IsBodyHtml = true;
Attachment objAttachment = new Attachment(memorystream, "AnAttachedImage.jpg");
emailEnquiry.Attachments.Add(objAttachment);
String ContentID = "TheAttachedImage";
objAttachment.ContentId = ContentID;
StringBuilder sb = new StringBuilder();
sb.Append("…lots of html here..<img src=’cid:" + ContentID + "’>…ending off with lots of html here too…");
emailEnquiry.Body = sb.ToString();
SmtpClient sendEnquiry = new SmtpClient();
sendEnquiry.Host = WebConfigUtil.GetAppSetting("MySmtpServerName");
sendEnquiry.Send(emailEnquiry);
return true;
}
catch (Exception er)
{
if (!HttpContext.Current.IsDebuggingEnabled)
{
return false;
}
else
throw er;
}
}
So there you go. I have simplified the method in this example by taking out logging etc, so hopefully it still works / makes sense. The part that took the longest to fathom was making the link between the attached image and the rendered html using the “cid:”.
Developer by day, husband and dad by night and dreaming about sport inbetween.