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

时间:2017-04-26 18:52:49

标签: c# html asp.net

我正在尝试根据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。这里有什么我想念的吗?

3 个答案:

答案 0 :(得分:1)

在对身体进行编码后,您可能需要在身体上尝试.Replace("\r\n", "<br />")

答案 1 :(得分:0)

你应该在这里使用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。 e.g:

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

答案 2 :(得分:0)

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

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