Formatting e-mail body HTML

前端 未结 1 552
一向
一向 2021-01-26 00:31

How would I go about making the body work with HTML format. what do I need to add and what line would I need to add it? I have tried MailMessage.IsBodyHtml = true; but that did

相关标签:
1条回答
  • 2021-01-26 01:30

    The HTML document you are creating isn't valid. E.g. you are opening two tags, but never close them. Also as far as I can tell your inline-styles aren't valid (unless there is something I am missing here).

    This line also looks like it should throw an error, when you are trying to run the program:

    body = <font size = "20" color = "red" style = "text-align:center;" > "ATTENTION\n\n" </ font >< br > +
    

    Instead of using string concatenation which is error prone and often leads to missing closing tags and other issues, an easy solution I sometimes use is to set up a valid HTML-template (e.g. in a resource file) that is populated by placeholders:

    <!DOCTYPE html>
    <html>
    <head>
        <style>
            .attention {
                text-align: center;
                font-size: 20px;
                color: red;
            }
            .content {{
                color: black;
                font-size: 10px;
            }}
        </style>
    </head>
    <body>
    <p class="attention">[PLACEHOLDER_TITLE]</p>
    
    <p class="content">[PLACEHOLDER_CONTENT]</p>
    
    <ol>
      <li>[PLACEHOLDER_LIST_ITEM_1]</li>
      <li>[PLACEHOLDER_LIST_ITEM_2]</li>
      <li>[PLACEHOLDER_LIST_ITEM_3]</li>
    </ol>
    </body>
    </html>
    

    These can then easily be replaced with the actual content later on and make the code much easier to read:

    string body = (String)GetLocalResourceObject("EmailTemplate");
    body.Replace("[PLACEHOLDER_TITLE]", title);
    body.Replace("[PLACEHOLDER_CONTENT]", content);
    ...
    

    Just to be clear: In your actual application you have to make sure that all characters are correctly escaped (in both the template and the replacement strings you are inserting into it).

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