Question

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

Was it helpful?

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.

OTHER TIPS

I have just ran this through LINQPad

string[] messages = new string[]{"First line in message", "Second Line in message", "Third Line in message"};

StringBuilder sbA = new StringBuilder();
StringBuilder sbB = new StringBuilder();
StringBuilder sbC = new StringBuilder();
StringBuilder sbD = new StringBuilder();

// New line for each string
foreach (var message in messages)
{
    sbA.AppendLine(message);
}

// New line for each string
foreach (var message in messages)
{
    sbB.Append(message + "\n");
}

// New line for each string
foreach (var message in messages)
{
    sbC.Append(message + System.Environment.NewLine);
}

//One Line
foreach (var message in messages)
{
    sbD.Append(message);
}


sbA.Dump();
sbB.Dump();
sbC.Dump();
sbD.Dump();

Each one performs as expected in a StringBuilder sense.

I suspect that you need to add "</br>" at the end of each AppendLine something like this (not tested):

MailMessage mail = new MailMessage(new MailAddress("someSender@email.com"), new MailAddress("someReceiver@email.com"));
string[] messages = new string[]{"First line in message", "Second Line in message", "Third Line in message"};

StringBuilder body = new StringBuilder();

body.AppendLine("<h2>My Message<h2></br>" );

foreach (var message in messages)
{
    body.AppendLine(message + "</br>");
}

mail.Body = body.ToString();

mail.Dump();

Gmail will remove explicit line breaks. This code works for me when sending to Gmail, as well as Outlook with proper line breaks intact. I am completely unable to replicate your issue without seeing what your messages[] array looks like. It may be possible that some formatting could be viewed as line breaks causing all to be stripped out? I have tampered with my example strings and I cannot get Outlook nor Gmail to strip the line breaks on me.

    private void SendMessage()
    {
        try
        {
            StringBuilder body = new StringBuilder();
            string[] messages = { "test with    a tab in it", "    test with     spaces", " \r\nTab, then line break", "\n\n\n\n\n\nlots of returns...", "                test spaces" };

            foreach (var msg in messages)
            {
                body.AppendLine(msg);
                //body.AppendLine(string.Empty);
            }


            using (MailMessage message = new MailMessage())
            {
                message.From = new MailAddress("you@test.com", "Your Display Name");
                message.ReplyToList.Add("reply-email@test.com");
                message.To.Add("to@test.com");
                message.Subject = "Test Line Break Message";
                message.IsBodyHtml = false;
                message.Priority = MailPriority.Normal;
                message.BodyEncoding = System.Text.Encoding.UTF8;
                message.Body = body.ToString();

                using (SmtpClient smtpClient = new SmtpClient())
                {
                    smtpClient.Host = "127.0.0.1";
                    smtpClient.Send(message);
                }
            }
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message);
        }
    }

I am going to assume somewhere in your code that builds or retrieves the messages array, something is happening to cause this issue. I would believe it to be fixable, but not without seeing how that part is coded.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top