MailMessage 类

定义

表示可以使用 SmtpClient 类发送的电子邮件。Represents an email message that can be sent using the SmtpClient class.

public ref class MailMessage : IDisposable
public class MailMessage : IDisposable
type MailMessage = class
    interface IDisposable
Public Class MailMessage
Implements IDisposable
继承
MailMessage
实现

示例

下面的代码示例演示如何创建和发送包含附件的电子邮件。The following code example demonstrates creating and sending an email message that includes an attachment.

static void CreateMessageWithAttachment( String^ server )
{
   
   // Specify the file to be attached and sent.
   // This example assumes that a file named Data.xls exists in the
   // current working directory.
   String^ file = L"data.xls";
   
   // Create a message and set up the recipients.
   MailMessage^ message = gcnew MailMessage( L"jane@contoso.com",L"ben@contoso.com",L"Quarterly data report.",L"See the attached spreadsheet." );
   
   // Create  the file attachment for this email message.
   Attachment^ data = gcnew Attachment(file, MediaTypeNames::Application::Octet);
   
   // Add time stamp information for the file.
   ContentDisposition^ disposition = data->ContentDisposition;
   disposition->CreationDate = System::IO::File::GetCreationTime( file );
   disposition->ModificationDate = System::IO::File::GetLastWriteTime( file );
   disposition->ReadDate = System::IO::File::GetLastAccessTime( file );
   
   // Add the file attachment to this email message.
   message->Attachments->Add( data );
   
   //Send the message.
   SmtpClient^ client = gcnew SmtpClient( server );
   
   // Add credentials if the SMTP server requires them.
   client->Credentials = CredentialCache::DefaultNetworkCredentials;
   client->Send( message );
   
   // Display the values in the ContentDisposition for the attachment.
   ContentDisposition^ cd = data->ContentDisposition;
   Console::WriteLine( L"Content disposition" );
   Console::WriteLine( cd );
   Console::WriteLine( L"File {0}", cd->FileName );
   Console::WriteLine( L"Size {0}", cd->Size );
   Console::WriteLine( L"Creation {0}", cd->CreationDate );
   Console::WriteLine( L"Modification {0}", cd->ModificationDate );
   Console::WriteLine( L"Read {0}", cd->ReadDate );
   Console::WriteLine( L"Inline {0}", cd->Inline );
   Console::WriteLine( L"Parameters: {0}", cd->Parameters->Count );
   IEnumerator^ myEnum1 = cd->Parameters->GetEnumerator();
   while ( myEnum1->MoveNext() )
   {
      DictionaryEntry^ d = safe_cast<DictionaryEntry^>(myEnum1->Current);
      Console::WriteLine( L"{0} = {1}", d->Key, d->Value );
   }

   data->~Attachment();
   client->~SmtpClient();
}


public static void CreateMessageWithAttachment(string server)
{
    // Specify the file to be attached and sent.
    // This example assumes that a file named Data.xls exists in the
    // current working directory.
    string file = "data.xls";
    // Create a message and set up the recipients.
    MailMessage message = new MailMessage(
        "jane@contoso.com",
        "ben@contoso.com",
        "Quarterly data report.",
        "See the attached spreadsheet.");

    // Create  the file attachment for this email message.
    Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
    // Add time stamp information for the file.
    ContentDisposition disposition = data.ContentDisposition;
    disposition.CreationDate = System.IO.File.GetCreationTime(file);
    disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
    disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
    // Add the file attachment to this email message.
    message.Attachments.Add(data);

    //Send the message.
    SmtpClient client = new SmtpClient(server);
    // Add credentials if the SMTP server requires them.
    client.Credentials = CredentialCache.DefaultNetworkCredentials;

    try
    {
        client.Send(message);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}", 
            ex.ToString());
    }
    // Display the values in the ContentDisposition for the attachment.
    ContentDisposition cd = data.ContentDisposition;
    Console.WriteLine("Content disposition");
    Console.WriteLine(cd.ToString());
    Console.WriteLine("File {0}", cd.FileName);
    Console.WriteLine("Size {0}", cd.Size);
    Console.WriteLine("Creation {0}", cd.CreationDate);
    Console.WriteLine("Modification {0}", cd.ModificationDate);
    Console.WriteLine("Read {0}", cd.ReadDate);
    Console.WriteLine("Inline {0}", cd.Inline);
    Console.WriteLine("Parameters: {0}", cd.Parameters.Count);
    foreach (DictionaryEntry d in cd.Parameters)
    {
        Console.WriteLine("{0} = {1}", d.Key, d.Value);
    }
    data.Dispose();
}

注解

MailMessage 类的实例用于构造使用 SmtpClient 类传输到 SMTP 服务器的电子邮件,以便进行传递。Instances of the MailMessage class are used to construct email messages that are transmitted to an SMTP server for delivery using the SmtpClient class.

当使用 MailMessage 初始化 MailMessage 对象时,可以将发件人、收件人、主题和电子邮件正文指定为参数。The sender, recipient, subject, and body of an email message may be specified as parameters when a MailMessage is used to initialize a MailMessage object. 还可以使用 MailMessage 对象上的属性设置或访问这些参数。These parameters may also be set or accessed using properties on the MailMessage object.

可以使用 MailMessage 类的以下属性设置消息的主邮件头和元素。The primary mail message headers and elements for the message may be set using the following properties of the MailMessage class.

邮件头或部分Mail header or part 属性Property
附件Attachments Attachments
密件抄送(BCC)Blind carbon copies (BCC) Bcc
抄送(CC)Carbon copies (CC) CC
Content-TypeContent-Type BodyEncoding
自定义标头编码Encoding for custom headers HeadersEncoding
邮件正文Message body Body
PriorityPriority Priority
Recipient To
答复Reply-To ReplyToList
寄信Sender From
SubjectSubject Subject

通过 MailMessage 类,应用程序还可以使用 Headers 属性访问消息的标头集合。The MailMessage class also allows an application to access the headers collection for the message using the Headers property. 尽管此集合是只读的(无法设置新集合),但可以在此集合中添加或删除自定义标头。While this collection is read-only (a new collection can not be set), custom headers can be added to or deleted from this collection. 发送 MailMessage 实例时,添加的任何自定义标头都将包括在内。Any custom headers added will be included when the MailMessage instance is sent. 在发送消息之前,集合中只包括专门添加到此集合中 Headers 属性的标头。Before a message is sent, only headers specifically added to this collection in the Headers property are included in the collection. 发送 MailMessage 实例后,Headers 属性还将包括使用 MailMessage 类的关联属性设置的标头,或在使用 MailMessage 来初始化 MailMessage 对象时传递的参数。After a the MailMessage instance is sent, the Headers property will also include headers that are set using the associated properties of the MailMessage class or parameters passed when a MailMessage is used to initialize a MailMessage object.

如果某些邮件头格式不正确,则可能会导致电子邮件损坏。If some mail headers are malformed, they could cause the email message to become corrupted. 因此,可以使用 MailMessage 类上的属性设置的标头集合中的任何邮件头都应使用 MailMessage 类属性设置,或者在 MailMessage 初始化 MailMessage 对象时作为参数传递。So any mail header in the headers collection that can be set using a property on the MailMessage class should only be set using the MailMessage class property or as a parameter passed when a MailMessage initializes a MailMessage object. 以下邮件头列表不应使用 Headers 属性进行添加,并且在发送消息时,将放弃或覆盖使用 Headers 属性设置的任何值:The following list of mail headers should not be added using the Headers property and any values set for these headers using the Headers property will be discarded or overwritten when the message is sent:

  • 密件抄送Bcc

  • CcCc

  • 内容-IDContent-ID

  • Content-LocationContent-Location

  • 内容传输编码Content-Transfer-Encoding

  • Content-TypeContent-Type

  • 日期Date

  • FromFrom

  • 重要性Importance

  • MIME-版本MIME-Version

  • PriorityPriority

  • 答复Reply-To

  • 寄信Sender

  • 功能To

  • X 优先级X-Priority

如果应用程序未使用 Headers 属性指定 X 发送方标头,则在发送消息时,MailMessage 类将创建一个。If the application does not specify an X-Sender header using the Headers property, the MailMessage class will create one when the message is sent.

使用 AlternateViews 属性指定采用不同格式的电子邮件副本。Use the AlternateViews property to specify copies of an email message in different formats. 例如,如果在 HTML 中发送消息,则可能还需要提供纯文本版本以防某些收件人使用无法显示 HTML 内容的电子邮件读者。For example, if you send a message in HTML, you might also want to provide a plain text version in case some of the recipients use email readers that cannot display HTML content. 有关演示如何使用替代视图创建消息的示例,请参阅 AlternateViewsFor an example that demonstrates creating a message with alternate views, see AlternateViews.

使用 Attachments 属性将附件添加到电子邮件中。Use the Attachments property to add attachments to an email message. 有关演示如何使用附件创建消息的示例,请参阅 AttachmentsFor an example that demonstrates creating a message with an attachment, see Attachments. 对 Send-mailmessage 调用 Dispose 还会对每个引用的附件调用 Dispose。Calling Dispose on the MailMessage also calls Dispose on each referenced Attachment.

收集电子邮件后,可以使用 SendSendAsync 方法发送电子邮件。After assembling your email message, you can send it by using the Send or SendAsync methods.

构造函数

MailMessage()

初始化 MailMessage 类的空实例。Initializes an empty instance of the MailMessage class.

MailMessage(MailAddress, MailAddress)

使用指定的 MailAddress 类对象初始化 MailMessage 类的新实例。Initializes a new instance of the MailMessage class by using the specified MailAddress class objects.

MailMessage(String, String)

使用指定的 String 类对象初始化 MailMessage 类的新实例。Initializes a new instance of the MailMessage class by using the specified String class objects.

MailMessage(String, String, String, String)

初始化 MailMessage 类的新实例。Initializes a new instance of the MailMessage class.

属性

AlternateViews

获取用于存储邮件正文的替代形式的附件集合。Gets the attachment collection used to store alternate forms of the message body.

Attachments

获取用于存储附加到此电子邮件的数据的附件集合。Gets the attachment collection used to store data attached to this email message.

Bcc

获取包含此电子邮件密件抄送 (BCC) 收件人的地址集合。Gets the address collection that contains the blind carbon copy (BCC) recipients for this email message.

Body

获取或设置邮件正文。Gets or sets the message body.

BodyEncoding

获取或设置用于邮件正文的编码。Gets or sets the encoding used to encode the message body.

BodyTransferEncoding

获取或设置用于邮件正文的传输编码。Gets or sets the transfer encoding used to encode the message body.

CC

获取包含此电子邮件抄送 (CC) 收件人的地址集合。Gets the address collection that contains the carbon copy (CC) recipients for this email message.

DeliveryNotificationOptions

获取或设置此电子邮件的发送通知。Gets or sets the delivery notifications for this email message.

From

获取或设置此电子邮件的发件人地址。Gets or sets the from address for this email message.

Headers

获取与此电子邮件一起传输的电子邮件标头。Gets the email headers that are transmitted with this email message.

HeadersEncoding

获取或设置此电子邮件的用户自定义标头使用的编码。Gets or sets the encoding used for the user-defined custom headers for this email message.

IsBodyHtml

获取或设置一个值,指示邮件正文是否为 HTML 格式。Gets or sets a value indicating whether the mail message body is in HTML.

Priority

获取或设置此电子邮件的优先级。Gets or sets the priority of this email message.

ReplyTo

获取或设置邮件的回复地址。Gets or sets the ReplyTo address for the mail message.

ReplyToList

获取邮件的回复地址的列表。Gets the list of addresses to reply to for the mail message.

Sender

获取或设置此电子邮件的发件人地址。Gets or sets the sender's address for this email message.

Subject

获取或设置此电子邮件的主题行。Gets or sets the subject line for this email message.

SubjectEncoding

获取或设置用于此电子邮件主题内容的编码。Gets or sets the encoding used for the subject content for this email message.

To

获取包含此电子邮件收件人的地址集合。Gets the address collection that contains the recipients of this email message.

方法

Dispose()

释放由 MailMessage 使用的所有资源。Releases all resources used by the MailMessage.

Dispose(Boolean)

释放由 MailMessage 占用的非托管资源,还可以另外再释放托管资源。Releases the unmanaged resources used by the MailMessage and optionally releases the managed resources.

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
ToString()

返回一个表示当前对象的 string。Returns a string that represents the current object.

(继承自 Object)

适用于