You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用CSharp开发邮件发送功能,HTML加粗标签显示异常的问题

解决C#邮件发送中HTML标签不生效的问题

问题根源是你的邮件被以纯文本格式解析,导致HTML标签被当作普通文本显示,而非渲染成对应格式。解决关键是明确告知邮件客户端正文为HTML格式,同时调整换行符为HTML兼容标签。

1. 核心设置:标记邮件正文为HTML格式

根据你使用的邮件发送库,做对应设置:

方案一:使用System.Net.Mail(.NET Framework或兼容项目)

string emailSubject = $"Welcome to ABC company";
string username = "testUser";
string userNewPassword = "testPass123";

// 注意:HTML中用<br>实现换行,替换原有的\n
string emailBody = $"<b>Username:</b> {username}<br>" +
                   $"<b>Password:</b> {userNewPassword}<br><br>";

MailMessage mail = new MailMessage();
mail.From = new MailAddress("your-email@example.com");
mail.To.Add("recipient@example.com");
mail.Subject = emailSubject;
mail.Body = emailBody;
// 关键:开启HTML正文解析模式
mail.IsBodyHtml = true;

using (SmtpClient smtp = new SmtpClient("smtp.example.com"))
{
    smtp.Credentials = new NetworkCredential("your-email@example.com", "your-password");
    smtp.Send(mail);
}

方案二:使用MailKit(推荐,适用于.NET Core/.NET 5+)

SmtpClient在新版.NET中已标记为过时,推荐使用MailKit库(需通过NuGet安装MailKit包):

using MimeKit;
using MailKit.Net.Smtp;

string emailSubject = $"Welcome to ABC company";
string username = "testUser";
string userNewPassword = "testPass123";

string emailBody = $"<b>Username:</b> {username}<br>" +
                   $"<b>Password:</b> {userNewPassword}<br><br>";

var message = new MimeMessage();
message.From.Add(new MailboxAddress("Sender", "your-email@example.com"));
message.To.Add(new MailboxAddress("Recipient", "recipient@example.com"));
message.Subject = emailSubject;

var bodyBuilder = new BodyBuilder();
// 设置HTML正文
bodyBuilder.HtmlBody = emailBody;
// 可选:添加纯文本版本,兼容不支持HTML的老旧邮件客户端
bodyBuilder.TextBody = $"Username: {username}\nPassword: {userNewPassword}\n\n";

message.Body = bodyBuilder.ToMessageBody();

using (var client = new SmtpClient())
{
    client.Connect("smtp.example.com", 587, MailKit.Security.SecureSocketOptions.StartTls);
    client.Authenticate("your-email@example.com", "your-password");
    client.Send(message);
    client.Disconnect(true);
}

2. 额外注意事项

  • HTML中的换行必须用<br>标签,\n无法在HTML格式邮件中生效
  • 若要兼容老旧邮件客户端,建议同时提供纯文本版本的正文
  • 确保SMTP服务器配置正确,且允许发送HTML格式邮件

内容的提问来源于stack exchange,提问作者Fatt Sky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 21:05:17