如何通过电子邮件发送换行符?

时间:2012-09-28 17:51:32

标签: asp.net email blogengine.net blog-engine

“\ n”或“< br />”都没有在工作中。我正在尝试通过电子邮件发送自定义表单的内容时插入换行符:

protected void SubmitBtn_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
    {
        StringBuilder mailBody = new StringBuilder();
        mailBody.Append("Company Name: " + companyText.Text.Trim() + "\n\n");
        mailBody.Append("Name: " + firstNameText.Text.Trim() + " " 
            + lastNameText.Text.Trim() + "\n\n");
        mailBody.Append("Email: " + emailText.Text.Trim() + "\n\n");

        if(!String.IsNullOrEmpty(tradeText.Text))
            mailBody.Append("Trade: " + tradeText.Text.Trim() + "\n\n");

            bool success = SendEmail(emailText.Text.Trim(), 
                companyText.Text.Trim(), "SubContractors Form Submission",
                    mailBody.ToString()); 
    }
}

private bool SendEmail(string email, string name, 
    string subject, string message)
{
    using (MailMessage mail = new MailMessage())
    {
        mail.From = new MailAddress(BlogSettings.Instance.Email, name);
        mail.ReplyTo = new MailAddress(email, name);

        mail.To.Add(BlogSettings.Instance.Email);
        mail.Subject = subject;
        mail.Body += message;

        if (Utils.SendMailMessage(mail).Length > 0)
        {
            return false;
        };
    }
    return true;
}

更新

我得到了< br />最终工作。它没有用的原因是因为这是我从联系表单中得到的原始代码:

mail.Body += message.Replace("\n\n", "<br />");

MailMessage.IsBodyHtml在核心库代码中设置为true。

3 个答案:

答案 0 :(得分:3)

您可以使用:

答案 1 :(得分:1)

您正在寻找Environment.NewLine

mailBody.Append("Email: " + emailText.Text.Trim() + Environment.NewLine);

答案 2 :(得分:1)

我认为使用AppendLine而非Append应该适用于您正在做的事情:

StringBuilder mailBody = new StringBuilder();

string company = companyText.Text.Trim();
string firstName = firstNameText.Text.Trim();
string lastName = lastNameText.Text.Trim();
string email = emailText.Text.Trim();
string trade = tradeText.Text.Trim();

mailBody.AppendFormat("Company Name: {0}", company).AppendLine();
mailBody.AppendFormat("Name: {0} {1}", firstName, lastName).AppendLine();
mailBody.AppendFormat("Email: {0}", email).AppendLine();

if(!string.IsNullOrEmpty(trade))
{
    mailBody.AppendFormat("Trade: {0}", trade).AppendLine();
}

bool success = SendEmail(email, company, "SubContractors Form Submission", 
    mailBody.ToString());

为了清晰起见,添加了AppendFormat()


创建变量以在少数情况下消除同一文本的多个.Trim()


根据此处所述改编AppendFormat().AppendLine() for performace:When do you use StringBuilder.AppendLine/string.Format vs. StringBuilder.AppendFormat?