如何在发送电子邮件时插入换行符



""或"
"都不起作用。我正在尝试在通过电子邮件发送自定义表单的内容时插入换行符:

protected void SubmitBtn_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
    {
        StringBuilder mailBody = new StringBuilder();
        mailBody.Append("Company Name: " + companyText.Text.Trim() + "nn");
        mailBody.Append("Name: " + firstNameText.Text.Trim() + " " 
            + lastNameText.Text.Trim() + "nn");
        mailBody.Append("Email: " + emailText.Text.Trim() + "nn");
        if(!String.IsNullOrEmpty(tradeText.Text))
            mailBody.Append("Trade: " + tradeText.Text.Trim() + "nn");
            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;
}

更新:

我最终得到了
的工作。它不起作用的原因是因为这是我从联系表单中获得的原始代码:

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

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

您可以使用:

  • 使用默认 MailMessage.IsBodyHtml = False 模式时的 Environment.NewLine 运算符;

  • 当 MailMessage.IsBodyHtml 模式为 True 时,通过"br"标记实现换行符。

您正在寻找Environment.NewLine .

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

我认为使用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()如下所述,用于性能:何时使用 StringBuilder.AppendLine/string。Format vs. StringBuilder.AppendFormat?

相关内容

  • 没有找到相关文章

最新更新