MailMessage.AlternateViews 属性

定义

获取用于存储邮件正文的替代形式的附件集合。

C#
public System.Net.Mail.AlternateViewCollection AlternateViews { get; }

属性值

可写的 AlternateViewCollection

示例

下面的代码示例演示如何创建和发送包含纯文本和 HTML 备用视图的电子邮件。

C#
public static void CreateMessageWithMultipleViews(string server, string recipients)
{
    // Create a message and set up the recipients.
    MailMessage message = new MailMessage(
        "jane@contoso.com",
        recipients,
        "This email message has multiple views.",
        "This is some plain text.");

    // Construct the alternate body as HTML.
    string body = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">";
    body += "<HTML><HEAD><META http-equiv=Content-Type content=\"text/html; charset=iso-8859-1\">";
    body += "</HEAD><BODY><DIV><FONT face=Arial color=#ff0000 size=2>this is some HTML text";
    body += "</FONT></DIV></BODY></HTML>";

    ContentType mimeType = new System.Net.Mime.ContentType("text/html");
    // Add the alternate body to the message.

    AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);
    message.AlternateViews.Add(alternate);

    // Send the message.
    SmtpClient client = new SmtpClient(server);
    client.Credentials = CredentialCache.DefaultNetworkCredentials;

    try
    {
        client.Send(message);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception caught in CreateMessageWithMultipleViews(): {0}",
            ex.ToString());
    }
    // Display the values in the ContentType for the attachment.
    ContentType c = alternate.ContentType;
    Console.WriteLine("Content type");
    Console.WriteLine(c.ToString());
    Console.WriteLine("Boundary {0}", c.Boundary);
    Console.WriteLine("CharSet {0}", c.CharSet);
    Console.WriteLine("MediaType {0}", c.MediaType);
    Console.WriteLine("Name {0}", c.Name);
    Console.WriteLine("Parameters: {0}", c.Parameters.Count);
    foreach (DictionaryEntry d in c.Parameters)
    {
        Console.WriteLine("{0} = {1}", d.Key, d.Value);
    }
    Console.WriteLine();
    alternate.Dispose();
}

注解

AlternateViews使用 属性可以指定不同格式的电子邮件副本。 例如,如果以 HTML 形式发送邮件,则可能还需要提供纯文本版本,以防某些收件人使用无法显示 HTML 内容的电子邮件阅读器。

若要向 MailMessage 对象添加备用视图,请为该视图创建 Attachment ,然后将其添加到 返回 AlternateViews的集合中。 Body使用 属性指定文本版本,并使用 AlternateViews 集合指定具有其他 MIME 类型的视图。 MediaTypeNames使用 类成员为备用视图指定 MIME 类型。

适用于

产品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1