Search code examples
c#asp.netstringbuilder

Adding new line using StringBuilder


I want to send user an email as below:
Here is the Verification Code
UserName: xyz
Code: xyz

Here is my all code about email:

StringBuilder emailMessage = new StringBuilder();
emailMessage.Append("Here is the Verification Code.");
emailMessage.Append(Environment.NewLine);
emailMessage.Append("UserName: " + UsernameTextBox.Text).AppendLine();
emailMessage.AppendLine();
emailMessage.Append("Code:  " + newCode);
MailMessage email = new MailMessage();
email.To.Add(new MailAddress(emailAddress));
email.Subject = "Subject";
email.Body = emailMessage.ToString();
email.IsBodyHtml = true;
  //Send Email; 
SmtpClient client = new SmtpClient();
client.Send(email);  

This code sends mail with a single line i.e. Here is the verification code. UserName: xyz Code: xyx
I tried using emailMessage.Append(Environment.NewLine); I also tried "\n", \r\n but nothing worked. what's wrong with it or where am I missing something?


Solution

  • Try AppendLine() when adding to the stringbuilder

    StringBuilder.AppendLine Method

    EDIT:

    If you are building HTML for the email then you need to append <br />. This will add a break and create a new line for you.