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

使用HTML模板发送邮件却显示纯文本的问题排查求助

问题

作为编程新手,我负责的邮件发送任务能正常发信,但邮件始终显示为纯文本。我发现代码里已经读取了HTML模板文件到template变量,但完全没用到它,而是自己拼接了HTML格式的emailBody传给SendGrid方法,怀疑这里有问题。附上C#代码:

if (oInf.Error == 0)
{
    string templateFilePath = AppDomain.CurrentDomain.BaseDirectory + "spwebfiles\\template.html";
    string template = "";

    using (StreamReader rd = new StreamReader(templateFilePath))
    {
        template = rd.ReadToEnd();
    }
//all these values comes from an an LIstobj, asume they are already filled.
    StringBuilder emailBody = new StringBuilder();
    emailBody.AppendLine($"Cliente: {companyName}<br>");
    emailBody.AppendLine("Módulo: Inventario<br>");
    emailBody.AppendLine($"Estación: {stationId}<br>");
    emailBody.AppendLine("<br>");

    foreach (var InventoryOffline_Model in oInf.ListObj)
    {
///sending a block of code, this will happen n# times as i might send several items or just 1
        string docName = THelperApp.GetDocName(InventoryOffline_Model.TranType);
        string block = string.Format(
            "<br>Fecha de creación del documento: {0} <br>Tipo de Documento: {1} <br>Mensaje de Error: {2} <br>" +
            "ID del documento: {3} <br>Intentos de Sincronización: {4} <br>",
            InventoryOffline_Model.DateE,
            docName,
            InventoryOffline_Model.MessageSync,
            InventoryOffline_Model.OfflineDocumentId,
            InventoryOffline_Model.Retry);

        emailBody.AppendLine(block); 
///sending a block of code, this will happen n# times as i might send several items or just 1
    }

    THelperSendMail.SendGrid("MyCompanyEmail.com",
        SendTo, //got this from appsetings
        "Alertas de sincronización",
        emailBody.ToString(),//taking the block as text. maybe this is the mistake?
        "My Company",
        true);

    if (THelperSendMail.Error)
    {
        _oResp.SendError(-248, "Ha ocurrido un error en el envío de correo electrónico");
    }
    else
    {
        _oResp.SendResponse(message: "");
    }
}
问题分析与解决步骤
  1. 未利用已读取的HTML模板
    你已经读取了template.html文件,但代码里完全没用到这个模板变量,相当于白加载了模板。如果模板里包含邮件的统一样式(比如头部、尾部、排版格式),必须把你拼接的emailBody内容插入到模板的对应位置,而不是直接用自己拼的内容。

  2. HTML转义字符错误
    你拼接内容时用了&lt;br&gt;,这是HTML转义后的字符。如果SendGrid要识别为HTML内容,应该直接用<br>,否则邮件会把&lt;br&gt;当成纯文本显示,不会解析成换行。

  3. SendGrid方法的HTML参数验证
    你传给SendGrid的最后一个true参数,要确认它确实是用来标记“发送HTML邮件”的开关。需要检查THelperSendMail.SendGrid的内部实现,确保它会根据这个参数把邮件的Content-Type设置为text/html——如果方法内部没处理这个参数,即使传了true也没用。

具体修改代码

  • 修正HTML转义字符:把所有&lt;br&gt;替换成<br>:

    StringBuilder emailBody = new StringBuilder();
    emailBody.AppendLine($"Cliente: {companyName}<br>");
    emailBody.AppendLine("Módulo: Inventario<br>");
    emailBody.AppendLine($"Estación: {stationId}<br>");
    emailBody.AppendLine("<br>");
    
    // 循环里的代码也同理修改
    string block = string.Format(
        "<br>Fecha de creación del documento: {0} <br>Tipo de Documento: {1} <br>Mensaje de Error: {2} <br>" +
        "ID del documento: {3} <br>Intentos de Sincronización: {4} <br>",
        InventoryOffline_Model.DateE,
        docName,
        InventoryOffline_Model.MessageSync,
        InventoryOffline_Model.OfflineDocumentId,
        InventoryOffline_Model.Retry);
    
  • 利用HTML模板:假设你的template.html里有一个占位符(比如{{EMAIL_CONTENT}})用来替换正文内容,修改代码如下:

    // 读取模板后,替换占位符
    string finalHtmlBody = template.Replace("{{EMAIL_CONTENT}}", emailBody.ToString());
    
    // 发送邮件时传入替换后的完整模板内容
    THelperSendMail.SendGrid("MyCompanyEmail.com",
        SendTo,
        "Alertas de sincronización",
        finalHtmlBody,
        "My Company",
        true);
    
  • 验证SendGrid方法:检查THelperSendMail.SendGrid的实现,确保它在isHtml参数为true时,设置邮件内容类型为HTML。比如内部应该有类似这样的逻辑:

    var msg = new SendGridMessage();
    msg.From = new EmailAddress(fromEmail, fromName);
    msg.AddTo(SendTo);
    msg.Subject = subject;
    if (isHtml)
    {
        msg.HtmlContent = body;
    }
    else
    {
        msg.PlainTextContent = body;
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 13:10:55