1

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

aw04
  • 9,954
  • 9
  • 52
  • 86
  • Why you think that new lines not added? – Hamlet Hakobyan Apr 08 '14 at 15:26
  • @HamletHakobyan Everything shows on the same line. – aw04 Apr 08 '14 at 15:27
  • What format is the mail message? If it's HTML you need `
    ` for line breaks.
    – Eli Arbel Apr 08 '14 at 15:27
  • In your working example, you are appending a line with a line break. In the one that doesn't, you are only using Append with only one line break. It's not clear to me the issue you are having. – LarsTech Apr 08 '14 at 15:28
  • @EliArbel It's not html – aw04 Apr 08 '14 at 15:30
  • @LarsTech I think you misunderstand, the "working" example appends two lines, as I'm using appendline and newline. The other examples I think should append one but I do not get a newline in the email. – aw04 Apr 08 '14 at 15:31
  • What returns `body.ToString().Split('\n').Length`? – Hamlet Hakobyan Apr 08 '14 at 15:31
  • @HamletHakobyan Good question. Just ran it and it does register the newline on split, I'm just not seeing the result for some reason. – aw04 Apr 08 '14 at 15:38
  • How do you confirm that no new lines are added? Is it in mail client? You said that _it's not html_ but maybe mail client treats it as such. – dkozl Apr 08 '14 at 15:38
  • Just show the result of expression in consloe/output/messsagebox. What you mean by `it does register the newline on split`? – Hamlet Hakobyan Apr 08 '14 at 15:40
  • @HamletHakobyan I mean it does split where the newlines are added, what exactly are you asking? It returns one greater than the length of my string[]... – aw04 Apr 08 '14 at 15:42
  • @dkozl I explicitly set IsBodyHtml to false, also why does my last example with two new lines work? – aw04 Apr 08 '14 at 15:43
  • Ok, then you have one string delimited by newlines. – Hamlet Hakobyan Apr 08 '14 at 15:44
  • Outlook and some other email clients have a tendency to remove line breaks thinking they are extra. Have you tried viewing in another email client? – justinlabenne Apr 08 '14 at 15:49
  • @justinlabenne Nice thought but no I sent it to my gmail and get the same thing. – aw04 Apr 08 '14 at 15:52
  • Add your code that sends the email, along with smtp Web.config settings if exists. – BateTech Apr 08 '14 at 16:08
  • Try setting email format to html and use
    for the line breaks
    – BateTech Apr 08 '14 at 16:11
  • I second the "add more code" comment, and also, can you check the properties of the email and ensure that they are "Content-Type: text/plain; charset="UTF-8". I cannot replicate the problem if IsBodyHtml=false. – justinlabenne Apr 08 '14 at 16:16
  • @BateTech I agree that will work, but it doesn't really answer the question. – aw04 Apr 08 '14 at 16:16
  • I will check the properties and update, hold on. – aw04 Apr 08 '14 at 16:17
  • What happens if you use "\r\n" instead of just "\n" ? http://www.webdeveloper.com/forum/showthread.php?144973-Plain-text-email-line-breaks-not-working&s=330b6fb743c622abcc139873e2f4e793&p=745552#post745552 – OnlineCop Apr 08 '14 at 16:42

3 Answers3

7

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.

Community
  • 1
  • 1
aw04
  • 9,954
  • 9
  • 52
  • 86
0

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.

justinlabenne
  • 783
  • 3
  • 6
  • Thanks for the answer, this actually adds an extra empty line though. In my question, you can see I was able to achieve this result. – aw04 Apr 08 '14 at 17:37
0

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();
CheGueVerra
  • 7,321
  • 3
  • 34
  • 48
  • See the answer I posted. You're right, the StringBuilder works as expected. Originally, I was not using html in the message but when I do adding does in fact work. – aw04 Apr 08 '14 at 17:32