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

C#发送HTML邮件时含空格的网络路径截断及编码异常问题求助

问题修复方案

核心问题分析

  1. HTML链接的href值未加引号包裹,邮件客户端会将空格识别为链接结束符,导致路径截断
  2. UNC共享路径未转换为标准file:// URI格式,客户端无法正确解析
  3. UrlEncode会将空格转为加号,不符合文件路径的编码规范

修复后的代码

public void sendEmail(List<string> toList)
{
    string from = "test@test.com";
    string UserName = ConfigurationManager.AppSettings["UserName"].ToString();
    string password = ConfigurationManager.AppSettings["password"].ToString();
    
    // 处理UNC路径:转换为标准file URI并正确编码空格
    string uncPath = @"\\pcm-test2\shared\PCM_GEO_TEST\NGS Forms";
    Uri fileUri = new Uri(uncPath);
    string encodedPath = fileUri.AbsoluteUri; // 自动转换为file:////pcm-test2/shared/PCM_GEO_TEST/NGS%20Forms
    
    // 构建带引号包裹的HTML链接
    StringBuilder TelURL = new StringBuilder()
        .Append("<a href=\"")
        .Append(encodedPath)
        .Append("\">HERE</a>"); 

    using (MailMessage mm = new MailMessage())
    {
        mm.From = new MailAddress(from);
        mm.To.Add(new MailAddress("rimi@test1.com"));
        mm.Subject = "Test subject";
        mm.Body = TelURL.ToString();
        mm.IsBodyHtml = true;

        SmtpClient client = new SmtpClient();
        client.Credentials = new NetworkCredential(UserName, password);
        client.Port = 111;
        client.EnableSsl = true;
        client.Host = "smtp.office365.com";
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.Send(mm);
    }
}

关键修复点

  • 给href值加引号:用双引号包裹链接地址,避免空格截断问题
  • 标准化File URI:通过Uri类自动将UNC路径转换为file:////server/share/path格式,确保客户端识别
  • 正确编码空格:Uri.AbsoluteUri会自动将空格转为%20,符合文件路径的编码规范,而非UrlEncode生成的加号

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 08:47:32