Monday, July 29, 2019

Send email with images using html template from C#

1. Create Email.html template.




2. Add images in it along with all the necessary placeholders to place values in it. example: ([Receiver]).

 public static void sendMail()
        {
            try
            {
                string recipientMailId = "xyz@abc.com";
                MailMessage Msg = new MailMessage();
                Msg.From = new MailAddress("tcon@somedomain.com", "TEST Console");
                Msg.To.Add(recipientMailId); Msg.Subject = "TEST";
                //Read this html email template                
                string templateToRead = string.Format("{0}\\{1}", HostingEnvironment.MapPath(@"~\EmailTemplates"), "email.html");
                StreamReader reader = new StreamReader(templateToRead);
                string readFile = reader.ReadToEnd();
                reader.Close();
                reader.Dispose();
                string StrContent = readFile;
                //Replace the placeholder  here           
                StrContent = StrContent.Replace("[Receiver]", "AnyName here");
                // Use this string as mail body.               
                string body = StrContent;
                var AltBody = AlternateView.CreateAlternateViewFromString(body, new System.Net.Mime.ContentType("text/html"));
                Msg.AlternateViews.Add(AltBody);
                Msg.IsBodyHtml = true;
                SmtpClient smtp = new SmtpClient("mailo2.dfc.com");
                smtp.Send(Msg);
                smtp.Dispose();
            }
            catch
            {
            } 
}


3. Call above method to Send email.

No comments:

Post a Comment