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

ASP.NET MVC中如何在C#邮件正文添加List数据为表格

ASP.NET MVC邮件中嵌入文档请求表格的实现

我需要在ASP.NET MVC应用发送的HTML格式邮件里,把List<ReqDocForMail>数据以文件类型|备注的表格形式展示,用于向用户请求文档,列表可能有1条或多条记录。现有邮件代码已写好,需要完成表格嵌入。

原有数据定义

List<ReqDocForMail> docList = new List<ReqDocForMail>();

public class ReqDocForMail
{
    public string FileType { get; set; }
    public string Note { get; set; }
}

修改后的完整邮件代码

string Subject = "Document Request for Task Number ";
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress("sendingmailaddress", "MailNameShows");
mailMessage.To.Add(User.Email_Primary);
mailMessage.Subject = Subject + TaskDetails.TaskNumber;

// 用StringBuilder构建表格,提升多数据场景下的性能
var tableBuilder = new StringBuilder();
// 表格基础样式保证邮件客户端兼容性
tableBuilder.Append(@"
<br />
<table border='1' cellpadding='4' cellspacing='0' style='border-collapse: collapse;'>
    <thead>
        <tr>
            <th>文件类型</th>
            <th>备注</th>
        </tr>
    </thead>
    <tbody>");

// 遍历生成表格行,转义特殊字符避免HTML格式错乱
foreach (var doc in docList)
{
    string safeFileType = HttpUtility.HtmlEncode(doc.FileType);
    string safeNote = HttpUtility.HtmlEncode(doc.Note);
    tableBuilder.AppendFormat(@"
        <tr>
            <td>{0}</td>
            <td>{1}</td>
        </tr>", safeFileType, safeNote);
}

tableBuilder.Append(@"
    </tbody>
</table>
<br />");

// 构建完整邮件正文并插入表格
string Body = @" 
  <html>
   <body>
    <p>Dear " + CusGen + Customer.Sur_Name + " " + Customer.Name + @",</p>
    <p>Thank you</p>
    <br />
    <p>Your Task is under processing.</p>
    <br />
    <p>To continue the task you need to upload the following documents.</p>
    <br />
    <p>Login to the Site and go to the <b>In Process Tasks</b></p>
    <br />
    <p>Open the request :" + TaskDetails.TaskNumber + @".</p>
    <br />
    <p>Move to the <b>Upload Documents</b> section and upload the following documents.</p>"
    + tableBuilder.ToString() +
@"   </body>
  </html>";

// 必须开启HTML正文模式
mailMessage.IsBodyHtml = true;
mailMessage.Body = Body;

关键注意事项

  • 使用StringBuilder替代直接字符串拼接,处理多条数据时性能更优
  • 用HttpUtility.HtmlEncode转义特殊字符(如<、>、&),防止HTML注入和格式混乱
  • 表格添加基础边框和内边距样式,适配不同邮件客户端(Outlook、Gmail等)的显示规则
  • 务必设置mailMessage.IsBodyHtml = true,否则HTML内容会被当作纯文本展示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 20:46:01