MailMessage MailMessage MailMessage MailMessage Class

定義

表示可以使用 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
繼承
MailMessageMailMessageMailMessageMailMessage
實作

範例

下列程式碼範例示範如何建立及傳送電子郵件訊息,其中包含附件。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:

  • BccBcc

  • CcCc

  • Content-IDContent-ID

  • Content-LocationContent-Location

  • Content-Transfer-EncodingContent-Transfer-Encoding

  • Content-TypeContent-Type

  • 日期Date

  • From

  • 重要性Importance

  • MIME 版本MIME-Version

  • 優先權Priority

  • 回覆至Reply-To

  • 寄件者Sender

  • To

  • X 優先順序X-Priority

如果應用程式未指定使用您建立 X 寄件者標頭Headers屬性,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.

之後組合您的電子郵件訊息時,您可以傳送使用它SendSendAsync方法。After assembling your email message, you can send it by using the Send or SendAsync methods.

建構函式

MailMessage() MailMessage() MailMessage() MailMessage()

初始化 MailMessage 類別的空執行個體。Initializes an empty instance of the MailMessage class.

MailMessage(MailAddress, MailAddress) MailMessage(MailAddress, MailAddress) MailMessage(MailAddress, MailAddress) 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, String) MailMessage(String, String) 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(String, String, String, String) MailMessage(String, String, String, String) MailMessage(String, String, String, String)

初始化 MailMessage 類別的新執行個體。Initializes a new instance of the MailMessage class.

屬性

AlternateViews AlternateViews AlternateViews AlternateViews

取得附件集合,用於儲存訊息主體的替代格式。Gets the attachment collection used to store alternate forms of the message body.

Attachments Attachments Attachments Attachments

取得附件集合,用於儲存附加到這個電子郵件訊息的資料。Gets the attachment collection used to store data attached to this email message.

Bcc Bcc Bcc Bcc

取得地址集合,其中包含這個電子郵件訊息的密件副本 (BCC) 收件者。Gets the address collection that contains the blind carbon copy (BCC) recipients for this email message.

Body Body Body Body

取得或設定訊息主體。Gets or sets the message body.

BodyEncoding BodyEncoding BodyEncoding BodyEncoding

取得或設定用來對訊息主體進行編碼的編碼方式。Gets or sets the encoding used to encode the message body.

BodyTransferEncoding BodyTransferEncoding BodyTransferEncoding BodyTransferEncoding

取得或設定用來對訊息主體進行編碼的傳輸編碼方式。Gets or sets the transfer encoding used to encode the message body.

CC CC CC CC

取得地址集合,其中包含這個電子郵件訊息的副本 (CC) 收件者。Gets the address collection that contains the carbon copy (CC) recipients for this email message.

DeliveryNotificationOptions DeliveryNotificationOptions DeliveryNotificationOptions DeliveryNotificationOptions

取得或設定這個電子郵件訊息的傳遞告知。Gets or sets the delivery notifications for this email message.

From From From From

取得或設定這個電子郵件訊息的寄件者地址。Gets or sets the from address for this email message.

Headers Headers Headers Headers

取得與這個電子郵件訊息一起傳送的電子郵件標頭。Gets the email headers that are transmitted with this email message.

HeadersEncoding HeadersEncoding HeadersEncoding HeadersEncoding

取得或設定編碼,此編碼會用於此電子郵件訊息中的使用者定義自訂標頭。Gets or sets the encoding used for the user-defined custom headers for this email message.

IsBodyHtml IsBodyHtml IsBodyHtml IsBodyHtml

取得或設定值,指出郵件訊息主體是否採用 HTML 格式。Gets or sets a value indicating whether the mail message body is in HTML.

Priority Priority Priority Priority

取得或設定這個電子郵件訊息的優先權。Gets or sets the priority of this email message.

ReplyTo ReplyTo ReplyTo ReplyTo

取得或設定郵件訊息的 ReplyTo 地址。Gets or sets the ReplyTo address for the mail message.

ReplyToList ReplyToList ReplyToList ReplyToList

取得郵件訊息回覆的地址清單。Gets the list of addresses to reply to for the mail message.

Sender Sender Sender Sender

取得或設定這個電子郵件訊息的寄件者地址。Gets or sets the sender's address for this email message.

Subject Subject Subject Subject

取得或設定這個電子郵件訊息的主旨。Gets or sets the subject line for this email message.

SubjectEncoding SubjectEncoding SubjectEncoding SubjectEncoding

取得或設定這個電子郵件訊息之主旨內容所用的編碼方式。Gets or sets the encoding used for the subject content for this email message.

To To To To

取得地址集合,其中包含這個電子郵件訊息的收件者。Gets the address collection that contains the recipients of this email message.

方法

Dispose() Dispose() Dispose() Dispose()

釋放 MailMessage 所使用的所有資源。Releases all resources used by the MailMessage.

Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

釋放 MailMessage 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。Releases the unmanaged resources used by the MailMessage and optionally releases the managed resources.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

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

(Inherited from Object)

適用於