Responsive Ads Here

Friday, May 3, 2013

Sending HTML emails with embedded images using C#

Email is extremely popular way of communication. To make this task easier, Microsoft .Net Framework contains System.Net.Mail namespace. Here are all classes that you need to work with emails. 

In this post we'll see which options are existing if you want to show an images in email. With images in HTML email you can achieve beautiful design and professional look of your newsletter or any other email. To add an image to email message you can use one of these three methods: - 
 -Add an image to email using absolute URL 
 - Add an image to email using file attachment
 - Add an image to email using Linked Resource class 

Every method has its own advantages and disadvantages. Depending of your specific needs you can choose the most appropriate method. 

As per my requirement i need to send HTML in email body. In that i have several images. If we use absolute URL, at any time is site is down then the images will not display. Using below code snippet  i am reading static HTML and replacing the strings with dynamic content and attaching as the HTML as Email Body.



var path = HttpContext.Current.Server.MapPath("~/index.htm"); //Getting HTML   
StreamReader reader = new StreamReader(path.ToString());  
string readFile = reader.ReadToEnd();  
string myString = "";  
myString = readFile;  
myString = myString.Replace("$$AccountNumber$$", agreementNo);  
MailMessage objMailMsg = new MailMessage(ConfigurationManager.AppSettings["FromStaticMail"].ToString(), toMail);  
objMailMsg.BodyEncoding = Encoding.UTF8;  
objMailMsg.Subject = ConfigurationManager.AppSettings["SubjectLine"].ToString();  
objMailMsg.Body = myString.ToString();  
objMailMsg.Priority = MailPriority.High;  
objMailMsg.IsBodyHtml = true;  
objMailMsg.Bcc.Add("XXXXXXX");  
Attachment attachmentTDS = new Attachment(Constants.PDF_Path + "\\" + "NOC_" + agreementNo + ".pdf");  
objMailMsg.Attachments.Add(attachmentTDS);  
//prepare to send mail via SMTP transport   
SmtpClient objSMTPClient = new SmtpClient();  
objSMTPClient.Host = ConfigurationManager.AppSettings["Static_Email_SMTP_Host"].ToString().Trim();  
objSMTPClient.Port =Convert.ToInt32(ConfigurationManager.AppSettings["Static_Email_SMTP_Port"].ToString());  
objSMTPClient.UseDefaultCredentials = false;  
objSMTPClient.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["Static_Email_User"].ToString().Trim(), ConfigurationManager.AppSettings["Static_Email_Password"].ToString().Trim());  
//objSMTPClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;  
objSMTPClient.Send(objMailMsg);  

In the above code snippet initially i am reading the html using stream reader and putting in to string variable. I am applying replace operation on string to replace the html variables with dynamic values. i.e $$AccountNumber$$ is available in html before sending an email i am replacing with the dynamic value. 

I am adding an attachment to the mail message and sending an email using Send method.

This block tells us how to send HTML emails. To send an Html mail we must first make MailMessage.IsBodyHtml to true and to send any images in the mail, we got to use AlternateView and LinkedResource concepts. The code goes as below.

string str = "<html><body><h1>Picture</h1><br/><img src=\"cid:image1\"></body></html>";
AlternateView av = AlternateView.CreateAlternateViewFromString(str,null,MediaTypeNames.Text.Html);
LinkedResource lr = new LinkedResource("E:\\Photos\\hello.jpg", MediaTypeNames.Image.Jpeg);
lr.ContentId = "image1";
av.LinkedResources.Add(lr);
m.AlternateViews.Add(av);
To reference images attached as linked sources from your Html message body, use cid:contentID in the image tag. And then specify the same name for the LinkedResource.ContentID.

No comments:

Post a Comment