How to create a multi line body in C# System.Net.Mail.MailMessage

C#Email

C# Problem Overview


If create the body property as

System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();

message.Body ="First Line \n second line";

I also tried

message.Body ="First Line" + system.environment + "second line";

Both of these were ignored when I received the message (using outlook).

Any ideas on how to get mutliple lines? I am trying to avoid html encoding so that the email will play nicer with spam filters.

thanks

C# Solutions


Solution 1 - C#

As per the comment by drris, if IsBodyHtml is set to true then a standard newline could potentially be ignored by design, I know you mention avoiding HTML but try using <br /> instead, even if just to see if this 'solves' the problem - then you can rule out by what you know:

var message = new System.Net.Mail.MailMessage();
message.Body = "First Line <br /> second line";

You may also just try setting IsBodyHtml to false and determining if newlines work in that instance, although, unless you set it to true explicitly I'm pretty sure it defaults to false anyway.

Also as a side note, avoiding HTML in emails is not necessarily any aid in getting the message through spam filters, AFAIK - if anything, the most you do by this is ensure cross-mail-client compatibility in terms of layout. To 'play nice' with spam filters, a number of other things ought to be taken into account; even so much as the subject and content of the mail, who the mail is sent from and where and do they match et cetera. An email simply won't be discriminated against because it is marked up with HTML.

Solution 2 - C#

In case you dont need the message body in html, turn it off:

message.IsBodyHtml = false;

then use e.g:

message.Body = "First line" + Environment.NewLine + 
               "Second line";

but if you need to have it in html for some reason, use the html-tag:

message.Body = "First line <br /> Second line";

Solution 3 - C#

Beginning each new line with two white spaces will avoid the auto-remove perpetrated by Outlook.

var lineString = "  line 1\r\n";
linestring += "  line 2";

Will correctly display:

line 1
line 2

It's a little clumsy feeling to use, but it does the job without a lot of extra effort being spent on it.

Solution 4 - C#

I usually like a StringBuilder when I'm working with MailMessage. Adding new lines is easy (via the AppendLine method), and you can simply set the Message's Body equal to StringBuilder.ToString() (... for the instance of StringBuilder).

StringBuilder result = new StringBuilder("my content here...");
result.AppendLine(); // break line

Solution 5 - C#

You need to enable IsBodyHTML

message.IsBodyHtml = true; //This will enable using HTML elements in email body
message.Body ="First Line <br /> second line";

Solution 6 - C#

The key to this is when you said

> using Outlook.

I have had the same problem with perfectly formatted text body e-mails. It's Outlook that make trash out of it. Occasionally it is kind enough to tell you that "extra line breaks were removed". Usually it just does what it wants and makes you look stupid.

So I put in a terse body and put my nice formatted text in an attachement. You can either do that or format the body in HTML.

Solution 7 - C#

Try this

IsBodyHtml = false,
BodyEncoding = Encoding.UTF8,
BodyTransferEncoding = System.Net.Mime.TransferEncoding.EightBit

If you wish to stick to using \r\n

I managed to get mine working after trying for one whole day!

Solution 8 - C#

Try using the verbatim operator "@" before your message:

message.Body = 
@"
FirstLine
SecondLine
"

Consider that also the distance of the text from the left margin affects on the real distance from the email body left margin..

Solution 9 - C#

Try using a StringBuilder object and use the appendline method. That might work.

Solution 10 - C#

Today I found the same issue on a Error reporting app. I don't want to resort to HTML, to allow outlook to display the messages I had to do (assuming StringBuilder sb):

sb.Append(" \r\n\r\n").Append("Exception Time:" + DateTime.UtcNow.ToString());

Solution 11 - C#

I realise this may have been answered before. However, i had this issue this morning with Environment.Newline not being preserved in the email body. The following is a full (Now Working with Environment.NewLine being preserved) method i use for sending an email through my program.(The Modules.MessageUpdate portion can be skipped as this just writes to a log file i have.) This is located on the main page of my WinForms program.

    private void MasterMail(string MailContents)
    {
        Modules.MessageUpdate(this, ObjApp, EH, 3, 25, "", "", "", 0, 0, 0, 0, "Master Email - MasterMail Called.", "N", MainTxtDict, MessageResourcesTxtDict);

        Outlook.Application OApp = new Outlook.Application();
        //Location of email template to use. Outlook wont include my Signature through this automation so template contains only that.
        string Temp = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + ResourceDetails.DictionaryResources("SigTempEmail", MainTxtDict);

        Outlook.Folder folder = OApp.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderDrafts) as Outlook.Folder;

        //create the email object.
        Outlook.MailItem TestEmail = OApp.CreateItemFromTemplate(Temp, folder) as Outlook.MailItem;

        //Set subject line.
        TestEmail.Subject = "Automation Results";

        //Create Recipients object.
        Outlook.Recipients oRecips = (Outlook.Recipients)TestEmail.Recipients;

        //Set and check email addresses to send to.
        Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("EmailAddressToSendTo");
        oRecip.Resolve();

        //Set the body of the email. (.HTMLBody for HTML Emails. .Body will preserve "Environment.NewLine")
        TestEmail.Body = MailContents + TestEmail.Body;
        try
        {
            //If outlook is not open, Open it.
            Process[] pName = Process.GetProcessesByName("OUTLOOK.EXE");
            if (pName.Length == 0)
            {
                System.Diagnostics.Process.Start(@"C:\Program Files\Microsoft Office\root\Office16\OUTLOOK.EXE");
            }

            //Send email
            TestEmail.Send();

            //Update logfile - Success.
            Modules.MessageUpdate(this, ObjApp, EH, 1, 17, "", "", "", 0, 0, 0, 0, "Master Email sent.", "Y", MainTxtDict, MessageResourcesTxtDict);
        }
        catch (Exception E)
        {
            //Update LogFile - Fail.
            Modules.MessageUpdate(this, ObjApp, EH, 5, 4, "", "", "", 0, 0, 0, 0, "Master Email - Error Occurred. System says: " + E.Message, "Y", MainTxtDict, MessageResourcesTxtDict);
        }
        finally
        {
            if (OApp != null)
            {
                OApp = null;
            }
            if (folder != null)
            {
                folder = null;
            }
            if (TestEmail != null)
            {
                TestEmail = null;
            }
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
    }

You can add multiple recipients by either including a "; " between email addresses manually, or in one of my other methods i populate from a Txt file into a dictionary and use that to create the recipients email addresses using the following snippet.

        foreach (KeyValuePair<string, string> kvp in EmailDict)
        {
            Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(kvp.Value);
            RecipientList += string.Format("{0}; ", kvp.Value);
            oRecip.Resolve();
        }

I hope at least some of this helps someone.

Solution 12 - C#

Adding . before \r\n makes it work if the original string before \r\n has no .

Other characters may work. I didn't try.

With or without the three lines including IsBodyHtml, not a matter.

Solution 13 - C#

Sometimes you don't want to create a html e-mail. I solved the problem this way :

Replace \n by \t\n

The tab will not be shown, but the newline will work.

Solution 14 - C#

Something that worked for me was simply separating data with a :

message.Body = FirstLine + ":" + SecondLine;

I hope this helps

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMaestro1024View Question on Stackoverflow
Solution 1 - C#Grant ThomasView Answer on Stackoverflow
Solution 2 - C#Mikael PuusaariView Answer on Stackoverflow
Solution 3 - C#Ron ThackerView Answer on Stackoverflow
Solution 4 - C#Justin DentonView Answer on Stackoverflow
Solution 5 - C#levinjayView Answer on Stackoverflow
Solution 6 - C#Charles KincaidView Answer on Stackoverflow
Solution 7 - C#s kView Answer on Stackoverflow
Solution 8 - C#Ciro CorvinoView Answer on Stackoverflow
Solution 9 - C#dotNet ZombieView Answer on Stackoverflow
Solution 10 - C#GilbertoView Answer on Stackoverflow
Solution 11 - C#DDuffyView Answer on Stackoverflow
Solution 12 - C#BobView Answer on Stackoverflow
Solution 13 - C#Mario FavereView Answer on Stackoverflow
Solution 14 - C#PoopaSaurasRexView Answer on Stackoverflow