【问题标题】:How to Properly Add CSS in a MailMessage如何在 MailMessage 中正确添加 CSS
【发布时间】:2013-12-02 08:17:49
【问题描述】:

我正在向 MailMessage.Body 写入一些 HTML,并希望包含一些 CSS 来格式化字体、表格等。我无法正确形成最终的 HTML。

例如:

public static void CreateMessageWithMultipleViews(string server, string recipients)
{
    // Create a message and set up the recipients.
    MailMessage message = new MailMessage("jane@contoso.com","joe@contoso.com");

    // Construct body as HTML. 
    message.Body = @"<html>
        <head>
            <style>
                p{
                    font-family:""Trebuchet MS"", Arial, Helvetica, sans-serif;
                    font-size:0.9em;
                    text-align:left;
                }
            </style>
        </head>
            <body>
                Some body text
            </body>
        </html>");

    // Set this property so that HTML renders
    message.IsBodyHtml = true;

    // Send the message.
    SmtpClient client = new SmtpClient(server);
    client.Credentials = CredentialCache.DefaultNetworkCredentials;
try 
{
    client.Send(message);
}
catch (Exception ex) 
{
    Console.WriteLine("Exception caught: {0}", 
    ex.ToString() );
}

我的电子邮件收件人都使用 Outlook 2010,这完全符合预期。但我很难喜欢它——在最终的电子邮件来源中有重复的&lt;html&gt;&lt;header&gt; 标签:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=us-ascii">
    </head>
<html>
    <head>
        <style>
            [..truncated..]

所以我的问题是,如何使用 MailMessage 正确设置电子邮件的 HTML 源代码,使其格式正确?我在 MailMessage 类中看到了一个 'Header' 属性,但那是用于邮件标题,而不是 HTML 标题。我是否需要将 CSS 代码放在其他地方?

【问题讨论】:

    标签: c# css .net email mailmessage


    【解决方案1】:

    请记住,我只需要在 Outlook 2010 中正确呈现,我将删除显式的 &lt;html&gt;&lt;header&gt; 标记并允许 MailMessage 处理这些标记:

    message.Body = @"
            <style>
                <!--
                p{
                    [truncating the rest...]
                }
                --->
            </style>";
    

    当我在 Outlook 中收到电子邮件时,这是源代码的格式,它适用于渲染,而且和以前一样不合逻辑(为了便于阅读,我更正了缩进):

    <html>
        <head>
        <meta http-equiv="Content-Type" content="text/html; charset=us-ascii"></head>
    <style>
        [css...]
    </style>
    <body>
        [content...]
    </body>
    </html>
    

    CSS 仍然不包含在标记中,但此时我很幸运 HTML 在 Outlook 客户端中正确呈现。

    【讨论】:

      猜你喜欢
      • 2011-11-01
      • 2014-02-09
      • 1970-01-01
      • 2015-11-08
      • 1970-01-01
      • 2011-03-17
      • 2011-06-20
      • 2021-04-19
      • 2017-01-17
      相关资源
      最近更新 更多