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

前端 未结 14 611
忘了有多久
忘了有多久 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:52

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

    0 讨论(0)
  • 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..

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

    You need to enable IsBodyHTML

    message.IsBodyHtml = true; //This will enable using HTML elements in email body
    message.Body ="First Line <br /> second line";
    
    0 讨论(0)
  • 2020-12-03 03:05

    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
    
    0 讨论(0)
  • 2020-12-03 03:05

    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.

    0 讨论(0)
  • 2020-12-03 03:06

    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.

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