How to Insert Line Breaks When Emailing?
-
04-07-2021 - |
Pergunta
Neither the "\n" or "<br />" are working. I'm trying to insert line breaks when emailing the contents of a custom form:
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;
}
UPDATE:
I got <br /> working eventually. Reason it didn't work was because this was the original code I got from the Contact form:
mail.Body += message.Replace("\n\n", "<br />");
MailMessage.IsBodyHtml
is set to true in the core library code.
Solução
You can use:
the Environment.NewLine operator when using the default MailMessage.IsBodyHtml = False mode;
implement a line-break via the "br" tag when the MailMessage.IsBodyHtml mode is True.
Outras dicas
You are looking for Environment.NewLine
.
mailBody.Append("Email: " + emailText.Text.Trim() + Environment.NewLine);
I think using AppendLine
rather than Append
should work for what you're doing:
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());
Added AppendFormat()
for clarity
created variables to eliminate multiple .Trim()
ing of the same text in a few cases
Adapted AppendFormat().AppendLine()
as described here for performace: When do you use StringBuilder.AppendLine/string.Format vs. StringBuilder.AppendFormat?