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

前端 未结 14 610
忘了有多久
忘了有多久 2020-12-03 02:45

If create the body property as

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

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


        
相关标签:
14条回答
  • 2020-12-03 02:50

    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";
    
    0 讨论(0)
  • 2020-12-03 02:50

    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());

    0 讨论(0)
  • 2020-12-03 02:51

    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!

    0 讨论(0)
  • 2020-12-03 02:51

    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.

    0 讨论(0)
  • 2020-12-03 02:52

    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.

    0 讨论(0)
  • 2020-12-03 02:52

    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.

    0 讨论(0)
提交回复
热议问题