Monday, October 5, 2009

How to embed image in C# Email


I had an interesting requirement to generate daily reports based on the accumulated sales data. And this Email will be sent to the respective Managers. Thought it would give a better picture if the email have the appropriate Brand images embedded on necessary places in report.

Following code was very much useful to embed an image in a system generated e-mail through C#.


Table objTable = new Table();

objTable.BorderStyle = BorderStyle.Solid;

objTable.BorderWidth = 1;

objTable.GridLines = GridLines.Both;

objTable.CellPadding = 5;

objTable.CellSpacing = 1;

objTable.BorderColor = System.Drawing.ColorTranslator.FromHtml("#035681");

objTable.Style.Add("Font-family", "Verdana");

objTable.Style.Add("Font-size", "14");

//Welcome TABLE CODE:

TableRow objTableRow_Welcome = new TableRow();

TableCell objTableCell_welcome1 = new TableCell();

objTableCell_welcome1.ColumnSpan = 1;

// Embeddind Image ID which is created below.

objTableCell_welcome1.Text = "<img src=\"cid:SampleImage\">";



SmtpClient smtp = new SmtpClient("YOUR SMTP CLIENT");

MailAddress sender = new MailAddress(" FAUZI @", "Fauzi");

MailAddress recipient = new MailAddress(" FAUZI @", "Recipient");

MailMessage m = new MailMessage(sender, recipient);

m.Subject = "Embed image with C# mail";

// Define the plain text alternate view and add to message

string plainTextBody = "Best viewed in Email client(Outlook) that supports HTML messages";

AlternateView plainTextView =


plainTextBody, null, MediaTypeNames.Text.Plain);


//Rendering Text from Created HTML TABLE in runtime

StringBuilder htmlBody = new StringBuilder();

StringWriter objStringWriter = new StringWriter(htmlBody);

HtmlTextWriter objHtmlTextWriter = new HtmlTextWriter(objStringWriter);


//Creating an Alternate view

AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlBody.ToString(), null, MediaTypeNames.Text.Html);

// Embedding Image here

LinkedResource sampleImage = new LinkedResource("logo.gif", MediaTypeNames.Image.Jpeg);

sampleImage.ContentId = "SampleImage";


//Adding the created Alternate view


// Finally, configure smtp or alternatively use the

// mailSettings


Hope it helps...

Please remember to give appropriate path of the image file.

Best Regards


No comments: