Saeid Mirzaei Saeid Mirzaei - 1 month ago 10
C# Question

How to send dynamic html content in mvc

I have an ASP.Net MVC application. I need to send html content from HTML-Editor. but I have problem with it.

This is my Html-Editor:

enter image description here

This is my code:

public void MailMessageHtml(string body, string subject, string from, IEnumerable<string> to)
{
var message = new MailMessage();
message.To.Add(new MailAddress("myemail@example.com"));
message.From = new MailAddress(_Settings.MailServer.UserName);
message.Subject = subject;
message.IsBodyHtml = true;

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

message.AlternateViews.Add(
AlternateView.CreateAlternateViewFromString(string.Empty, new ContentType("text/plain")));

message.AlternateViews.Add(htmlBody);

using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = _Settings.MailServer.UserName,
Password = _Settings.MailServer.Password
};
smtp.Credentials = credential;
smtp.Host = _Settings.MailServer.IPAddress;
smtp.Port = _Settings.MailServer.Port;
smtp.EnableSsl = _Settings.MailServer.EnableSSL;
smtp.Send(message);
}
}


but the html content in Email's body has shown like this:

enter image description here

What should I do?

Answer

You need to Decode the content before passing the content to the body.

body = HttpUtility.HtmlDecode(body);

Just this.