ASP.NET SMTP邮件HTML格式失效问题咨询
Hey Marcus, let's figure out why your HTML email tags are showing up as plain text instead of rendering properly—even with IsBodyHtml = true set. Here are the most common culprits and fixes:
1. Your HTML Content Is Being HTML-Encoded
The biggest suspect here is that your order detail HTML is already escaped (e.g., <br/> got turned into <br/>) before it reaches the MailMessage.Body property. This usually happens if you're pulling content from a source that automatically encodes HTML (like a database field, Razor view output, or a sanitized input).
Fix: Decode the HTML Before Assigning It
Use HttpUtility.HtmlDecode() to convert those escaped characters back to raw HTML tags:
// Replace your existing body assignment with this mail.Body = HttpUtility.HtmlDecode(orderDetailsHtml);
Make sure you add a reference to System.Web (or System.Net.Http if you're using .NET Core/.NET 5+) to access this method.
2. Accidental Overwrite of IsBodyHtml
Double-check that you aren't setting IsBodyHtml = true and then accidentally changing it later in your code. For example:
var mail = new MailMessage(fromAddress, toAddress); mail.IsBodyHtml = true; // Correctly set here // ... some other code ... mail.Body = "Your order details..."; // Oops! Did someone add this line later? mail.IsBodyHtml = false;
Debug through your code to confirm the property stays true right before sending.
3. Test with a Minimal HTML Payload
To rule out issues with your dynamic order content, send a simple test email first:
var testMail = new MailMessage(fromAddress, toAddress) { Subject = "Test HTML Email", Body = "<h1>Order Confirmation</h1><br/>Thank you for your purchase!", IsBodyHtml = true }; // Send this test email and see if the <br/> renders as a line break
If this test works, the problem is definitely in how you're generating your dynamic order detail HTML—go back and check that your string concatenation or template isn't escaping tags.
4. Check for Hidden Escape Characters
Sometimes when building HTML dynamically (e.g., with StringBuilder or string interpolation), you might accidentally introduce extra escape characters. Debug your orderDetailsHtml variable to see its actual value—if you see <br/> instead of <br/>, that's the smoking gun.
内容的提问来源于stack exchange,提问作者Marcus Neo

