HttpUtility.HtmlEncode loosing HTML tags in email

Muhammad Taqi 1 Reputation point
2021-03-26T10:16:01.337+00:00

I'm trying to send emails which contains html tags using the following code.

            string host = "smtp.office365.com", subject = "", fromAddr = "fromAddress";
            SmtpClient client = new SmtpClient(host, 587);
            MailMessage msg = new MailMessage();
            msg.From = new MailAddress(fromAddr);
            msg.Subject = subject;
            msg.IsBodyHtml = true;
            string emailBody = "Hello <strong>World</strong>";
            msg.Body = HttpUtility.HtmlEncode(emailBody);
            string toAddrList = "toaddress";
            foreach (string addr in toAddrList.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
            {
                msg.To.Add(addr.Trim());
            }
            System.Net.NetworkCredential credential = new System.Net.NetworkCredential("email", "pass", ""); 
            client.UseDefaultCredentials = false;
            client.Credentials = credential; 
            client.EnableSsl = true; 
            client.Send(msg);

The emails are being sent but html tags are not being render, emails are received with simple text like ![81855-image.png][1] But if I remove System.Web.HttpUtility.HtmlEncode method and pass the emailBody as it is, then it renders html tags properly in email. Can someone please tell me how can I make it work so that I dont have to remove the System.Web.HttpUtility.HtmlEncode method and keeping html tags as well. Thanks

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,218 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 112K Reputation points
    2021-03-26T10:24:42.897+00:00

    Maybe use msg.Body = System.Web.HttpUtility.HtmlDecode( some_encoded_string ) if you have to send encoded strings.