繁体   English   中英

在 HTML 电子邮件正文的字符串中添加换行符

[英]Adding Newline in string for HTML email body

我正在尝试根据 FormView 中的标签生成具有一些基本格式的电子邮件。 我要走Process.Start("mailto:...而不是 System.Net.Mail 这样电子邮件会在默认电子邮件客户端中打开,让用户有机会编辑 To: CC: 等,而无需创建新表单只是为了处理这个问题。我有以下代码隐藏来处理“电子邮件表单”按钮,用于通过电子邮件发送网络表单的 URL。

protected void fvBF_ItemCommand(object sender, FormViewCommandEventArgs e)
{
    if (e.CommandName == "Email")
    {
        Label lblBFID = (Label)fvBookingForm.FindControl("lblBFID");
        Label lblProjectID = (Label)fvBookingForm.FindControl("lblProjectNum");
        Label lblProjectName = (Label)fvBookingForm.FindControl("lblProjectName");
        Label lblReleaseName = (Label)fvBookingForm.FindControl("lblReleaseName");
        Label lblPMName = (Label)fvBookingForm.FindControl("lblPM");

        String strReleaseName = String.IsNullOrEmpty(lblReleaseName.Text) ? "[Description]" : lblReleaseName.Text;

        String pmFirst = lblPMName.Text.ToString().Split()[0];
        String pmLast = lblPMName.Text.ToString().Split()[1];

        String strSubject = "BF " + lblBFID.Text + " - " + lblProjectName.Text  + " - Release " + strReleaseName;
        String strBody = "A Booking Form for Project #"+ lblProjectID.Text + " - " + lblProjectName.Text + 
            " - Release " + strReleaseName + " has been created or modified. \n\n" + Request.Url.ToString();

        Process.Start("mailto:" + pmFirst + "." + pmLast + "@company.com?subject=" +
            HttpUtility.HtmlAttributeEncode(strSubject) + "&body=" +
            HttpUtility.HtmlAttributeEncode(strBody).Replace("\n", Environment.NewLine));
    }
}

但是,当生成电子邮件时,正文中“A Booking Form...”句子和 URL 之间没有换行符。 我试过将 Environment.NewLine 直接放在字符串中。

...created or modified. " + Environment.Newline + Environment.NewLine + Request.Url.ToString();

这基本上给了我相同的结果。 我试过用<br />替换 \n ,它不添加换行符,并且由于某种原因,也不显示 URL。 我只能猜测问题与 HtmlAttributeEncode() 有关并让它正确解析 NewLine。 我在这里缺少什么吗?

完成正文编码,您可能想在正文上尝试.Replace("\r\n", "<br />")

您应该在这里使用StringBuilder而不是 String。

然后您可以执行以下操作:

StringBuilder builder = new StringBuilder();
builder.AppendLine(string.Format("A Booking Form for Project #{0} - {1}",lblProjectID.Text, lblProjectName.Text));
builder.AppendLine(string.Format(" - Release {0}  has been created or modified.", strReleaseName));
builder.AppendLine();
builder.AppendLine(Request.Url.ToString());
String strBody = builder.ToString();

您还可以在字符串创建中包含 (char)10 和 (char)13。 例如:

string.Format("First Line{0}{1}Second Line", (char)10, (char)13);

Model.Message = "我的消息\n第二条消息";

然后将此样式添加到字符串标签 style="white-space: pre-line;" 示例<h3 style="white-space: pre-line;">@Model.Message</h3>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM