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);
//mMailMessage.Attachments.Add(log_attachment);

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;
htmlView.LinkedResources.Add(imagelink);
mMailMessage.AlternateViews.Add(htmlView);

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


 

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. There are many ways to send emails with images. The most commonly used files are C# pdf to image and word, excel and other files are converted to png, jpg and other image formats, and then sent, see your method, it is very advanced, great .

    ReplyDelete

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