dinesh.k
dinesh.k

Reputation: 197

Send Mail in HTML Format using mvc

I need to send the mail in HTML Format. I googled lot but i could not able to get the expected result as html format. Can anyone help what i am missing in this following code to get the html format mail.

C# Code

         MailAddress sender = new MailAddress(ConfigurationManager.AppSettings["smtpUser"]);
             string MailId = Convert.ToString(Session["EmailID"]);
     SmtpClient smtp = new SmtpClient()
                    {
                        Host = ConfigurationManager.AppSettings["smtpServer"],
                        Port = Convert.ToInt32(ConfigurationManager.AppSettings["smtpPort"]),
                        UseDefaultCredentials = false,
                        EnableSsl = true,
                        Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["smtpUser"], ConfigurationManager.AppSettings["smtpPass"]),
                        DeliveryMethod = SmtpDeliveryMethod.Network
                    };
  System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
                string text = "<table><tr><td>EmpId</td><td>Emp name</td><td>age</td></tr><tr><td>value</td><td>value</td><td>value</td></tr></table>";
                msg.From = sender;
                msg.To.Add(MailId);
                msg.Body = text;                
                msg.IsBodyHtml = true;
                mail.Subject = "Password Credentials"; 
 smtp.Send(mail.From, mail.To, mail.Subject, msg.Body); 

Output

enter image description here

Upvotes: 1

Views: 2068

Answers (1)

Vijay Gill
Vijay Gill

Reputation: 1518

Not fully working example, but a hint is given below:

var msg = new MailMessage();

var htmlBody = AlternateView.CreateAlternateViewFromString(your_html_string_in_variable, Encoding.UTF8,"text/html");

msg.AlternateViews.Add(htmlBody);

IsBodyHtml = true;

... and do the rest of the stuff

Upvotes: 1

Related Questions