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 類別的實例是用來建立傳送到 SMTP 伺服器的電子郵件訊息,以便使用 SmtpClient 類別進行傳遞。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
優先權Priority Priority
收件者Recipient To
回復Reply-To ReplyToList
發送者Sender From
主旨Subject 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

  • 內容識別碼Content-ID

  • 內容位置Content-Location

  • 內容傳輸-編碼Content-Transfer-Encoding

  • Content-TypeContent-Type

  • 日期Date

  • From

  • 重要性Importance

  • MIME 版本MIME-Version

  • 優先權Priority

  • 回復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)

使用指定的 MailMessage 類別物件,初始化 MailAddress 類別的新執行個體。Initializes a new instance of the MailMessage class by using the specified MailAddress class objects.

MailMessage(String, String)

使用指定的 MailMessage 類別物件,初始化 String 類別的新執行個體。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

取得或設定郵件訊息的 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 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。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 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(繼承來源 Object)
ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)

適用於