Reputation: 330
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?
Upvotes: 1
Views: 19146
Reputation: 320
an extension method could simplify code...
public static StringBuilder AppendHtmlLine(this StringBuilder sb, string line) {
return sb.Append(line + "<br>");
}
then you just call
stringBuilder.AppendHtmlLine("Here is the Verification Code.");
and lines will be terminated with <br>
Upvotes: 0
Reputation: 4059
This will do Here
StringBuilder emailMessage = new StringBuilder();
emailMessage.AppendLine("Here is the Verification Code.");
// emailMessage.Append(Environment.NewLine);
emailMessage.AppendLine("UserName: " + UsernameTextBox.Text);
emailMessage.AppendLine();
emailMessage.AppendLine("Code: " + newCode);
Upvotes: 0
Reputation: 40970
The answer of your question is, use AppendLine()
method. But as you are sending email I would strongly recommended you to create a HTML template which contains the placeholder for actual value and then replace the placeholder with actual values and then send that content to the email body with IsBodyHtml=true
.
This will help you in future as well like when you want to change the format of the email you don't need to build or deploy your project, you just need to edit the template.
StringBuilder sb = new StringBuilder();
sb.Append(File.ReadAllText(HttpContext.Current.Server.MapPath("~/EmailTemplate/template.htm")));
//Replace literals
sb.Replace("<%Name%>", "FirstName");
sb.Replace("<%EmailAddress%>", "Email");
sb.Replace("<%Password%>", "password");
Upvotes: 2
Reputation: 26209
you can use <br/>
tag and set/add the Content AlternateViews
text/html
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlContent);
htmlView.ContentType = new System.Net.Mime.ContentType("text/html");
<MailMessageObject>.AlternateViews.Add(htmlView);
Upvotes: 0
Reputation: 13620
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.
Upvotes: 10