Search code examples
c#outlookgmailnewlinestringbuilder

Line breaks being removed from email body


I'm generating a simple email using the System.Net.Mail.MailMessage class and building the body with a StringBuilder. I'm looping through a string[] and trying to append a new line each time. The problem I'm having is that I can't seem to generate a single new line each time. I can either get two or none.

What I've tried:

foreach (var message in messages)
{
    body.AppendLine(message);
}

foreach (var message in messages)
{
    body.Append(message + "\n");
}

foreach (var message in messages)
{
    body.Append(message + System.Environment.NewLine);
}

I've also tried with string.Format().

For each example above, I get the same result. No new line being generated.

When I try the following, however, I get the expected result. A new line with an empty line in between.

foreach (var message in messages)
{
    body.AppendLine(message + System.Environment.NewLine);
}

Why is it doing this and what can I do to just get a single new line each time?

Update:

So I've found that Outlook and probably Gmail (haven't tested others) are actually removing some line breaks and not others. Does anyone know why or how they determine what to remove?

enter image description here


Solution

  • When I checked the email in Outlook, I got a tiny info message saying "Extra line breaks in this message were removed" and the option to restore them. Gmail gave no such indication (that I found) but I must assume it removed them as well.

    Interestingly enough I had line breaks elsewhere in the body that worked as expected, only the ones in the loop were deemed "extra".

    I have modified my code to build the email body using html.

    IsBodyHtml = true
    

    If anyone knows of a way to prevent this, or what causes certain line breaks to be removed, please let me know.

    Update:

    Once I knew what I was looking for, I found this post which helps to explain things and gives some alternate solutions. I did not try any of them, as I think using html is the better solution in my case.