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#.
Code:
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\">";
objTableRow_Welcome.Cells.Add(objTableCell_welcome1);
objTable.Rows.Add(objTableRow_Welcome);
SmtpClient smtp = new SmtpClient("YOUR SMTP CLIENT");
MailAddress sender = new MailAddress(" FAUZI @ CHENNAI.com", "Fauzi");
MailAddress recipient = new MailAddress(" FAUZI @ INDIA.com", "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 =
AlternateView.CreateAlternateViewFromString(
plainTextBody, null, MediaTypeNames.Text.Plain);
m.AlternateViews.Add(plainTextView);
//Rendering Text from Created HTML TABLE in runtime
StringBuilder htmlBody = new StringBuilder();
StringWriter objStringWriter = new StringWriter(htmlBody);
HtmlTextWriter objHtmlTextWriter = new HtmlTextWriter(objStringWriter);
objTable.RenderControl(objHtmlTextWriter);
//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";
htmlView.LinkedResources.Add(sampleImage);
//Adding the created Alternate view
m.AlternateViews.Add(htmlView);
// Finally, configure smtp or alternatively use the
// system.net mailSettings
smtp.Send(m);
Hope it helps...
Please remember to give appropriate path of the image file.
Best Regards
Fauzi
No comments:
Post a Comment