Search This Blog

Wednesday, April 13, 2011

C# sending mail with embedded image; Image content id; System.Net.Mail.MailMessage; C# embedding image in attachment into HTML email

What we want to do is send an email with embedded image. The email is of course in HTML format. What DID not work for me is:

- setting mail body type to HTML, adding attachment of png format and content id set to ID_IMAGE  and using <img src=”cid:ID_IMAGE”>

I did it in a different way:

You can define AlternateView and add LinkedResource to it of type = “image/png”. Then define image’s content id and transfer encoding type. This solution does not prevent you from adding different attachments as well.


using System.Net.Mail;
using System.Net.Mime;

string subject = "some subject";
string body += "<img alt=\"\" src=\"@@IMAGE@@\">" + "<br/>";

MailMessage mMailMessage = new MailMessage();
mMailMessage.From = new MailAddress(from);
mMailMessage.To.Add(new MailAddress(to));
//mMailMessage.Bcc.Add(new MailAddress(bcc));
//mMailMessage.CC.Add(new MailAddress(cc));
mMailMessage.Subject = subject;
mMailMessage.Body = body;
mMailMessage.Priority = MailPriority.Normal;

//you can add another attachments as well
//Attachment log_attachment = new Attachment(Program._LOG_FILE_LOCALISATION, MediaTypeNames.Text.Plain);

string contentID = Path.GetFileName(Program._VL_LOGO_LOCALISATION).Replace(".", "") + "@domain";
body = body.Replace("@@IMAGE@@", "cid:" + contentID);

AlternateView htmlView = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
LinkedResource imagelink = new LinkedResource(Program._VL_LOGO_LOCALISATION, "image/png");
imagelink.ContentId = contentID;
imagelink.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;

SmtpClient mSmtpClient = new SmtpClient();
mSmtpClient.Host = "";
return true;



If you like this post, please leave a comment :)