更新:2007 年 11 月
允許應用程式使用 Simple Mail Transfer Protocol (SMTP) 傳送電子郵件。
命名空間:
System.Net.Mail 組件:
System (在 System.dll 中)
Dim instance As SmtpClient
public ref class SmtpClient
SmtpClient 類別是用來傳送電子郵件給 SMTP 主機以進行傳遞。下表中所示的類別是用來建構可使用 SmtpClient 傳送的電子郵件訊息。
若要使用 SmtpClient 建構和傳送電子郵件訊息,您必須指定下列資訊:
若要在電子郵件訊息中加入附件,請先使用 Attachment 類別建立附件,然後使用 MailMessage..::.Attachments 屬性將它加入訊息中。根據收件者所用的電子郵件讀取器 (Reader) 和附件的檔案類型而定,某些收件者可能無法讀取附件。對於無法以原始形式顯示附件的用戶端,您可以使用 MailMessage..::.AlternateViews 屬性為其指定替代檢視。
您可以使用應用程式或電腦組態檔,指定所有 SmtpClient 物件的預設主機、連接埠和認證值。如需詳細資訊,請參閱<mailSettings> 項目 (網路設定)。
若要傳送電子郵件訊息,並在等候電子郵件傳送到 SMTP 伺服器時封鎖,請使用其中一個同步 Send 方法。若要允許程式的主執行緒在傳送電子郵件時繼續執行,請使用其中一個非同步 SendAsync 方法。當 SendAsync 作業完成時,會引發 SendCompleted 事件。若要接收這個事件,您必須將 SendCompletedEventHandler 委派 (Delegate) 加入 SendCompleted。SendCompletedEventHandler 委派必須參考可以處理 SendCompleted 事件之告知的回呼方法。若要取消非同步電子郵件傳送,請使用 SendAsyncCancel 方法。
SMTP 是在 RFC 2821 中定義,該 RFC 可於 http://www.ietf.org 取得。
在下列程式碼範例中,示範了如何以非同步方式傳送電子郵件訊息。
using System;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading;
using System.ComponentModel;
namespace Examples.SmptExamples.Async
{
public class SimpleAsynchronousExample
{
static bool mailSent = false;
private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
// Get the unique identifier for this asynchronous operation.
String token = (string) e.UserState;
if (e.Cancelled)
{
Console.WriteLine("[{0}] Send canceled.", token);
}
if (e.Error != null)
{
Console.WriteLine("[{0}] {1}", token, e.Error.ToString());
} else
{
Console.WriteLine("Message sent.");
}
mailSent = true;
}
public static void Main(string[] args)
{
// Command line argument must the the SMTP host.
SmtpClient client = new SmtpClient(args[0]);
// Specify the e-mail sender.
// Create a mailing address that includes a UTF8 character
// in the display name.
MailAddress from = new MailAddress("jane@contoso.com",
"Jane " + (char)0xD8+ " Clayton",
System.Text.Encoding.UTF8);
// Set destinations for the e-mail message.
MailAddress to = new MailAddress("ben@contoso.com");
// Specify the message content.
MailMessage message = new MailMessage(from, to);
message.Body = "This is a test e-mail message sent by an application. ";
// Include some non-ASCII characters in body and subject.
string someArrows = new string(new char[] {'\u2190', '\u2191', '\u2192', '\u2193'});
message.Body += Environment.NewLine + someArrows;
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Subject = "test message 1" + someArrows;
message.SubjectEncoding = System.Text.Encoding.UTF8;
// Set the method that is called back when the send operation ends.
client.SendCompleted += new
SendCompletedEventHandler(SendCompletedCallback);
// The userState can be any object that allows your callback
// method to identify this send operation.
// For this example, the userToken is a string constant.
string userState = "test message1";
client.SendAsync(message, userState);
Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
string answer = Console.ReadLine();
// If the user canceled the send, and mail hasn't been sent yet,
// then cancel the pending operation.
if (answer.StartsWith("c") && mailSent == false)
{
client.SendAsyncCancel();
}
// Clean up.
message.Dispose();
Console.WriteLine("Goodbye.");
}
}
}
#using <System.dll>
using namespace System;
using namespace System::Net;
using namespace System::Net::Mail;
using namespace System::Net::Mime;
using namespace System::Threading;
using namespace System::ComponentModel;
static bool mailSent;
static void SendCompletedCallback(Object^ sender, AsyncCompletedEventArgs^ e)
{
// Get the unique identifier for this asynchronous
// operation.
String^ token = (String^) e->UserState;
if (e->Cancelled)
{
Console::WriteLine("[{0}] Send canceled.", token);
}
if (e->Error != nullptr)
{
Console::WriteLine("[{0}] {1}", token,
e->Error->ToString());
} else
{
Console::WriteLine("Message sent.");
}
mailSent = true;
}
int main(array<String^>^ args)
{
if (args->Length > 1)
{
// Command line argument must the the SMTP host.
SmtpClient^ client = gcnew SmtpClient(args[1]);
// Specify the e-mail sender.
// Create a mailing address that includes a UTF8
// character in the display name.
MailAddress^ from = gcnew MailAddress("jane@contoso.com",
"Jane " + (wchar_t)0xD8 + " Clayton",
System::Text::Encoding::UTF8);
// Set destinations for the e-mail message.
MailAddress^ to = gcnew MailAddress("ben@contoso.com");
// Specify the message content.
MailMessage^ message = gcnew MailMessage(from, to);
message->Body = "This is a test e-mail message sent" +
" by an application. ";
// Include some non-ASCII characters in body and
// subject.
String^ someArrows = gcnew String(gcnew array<wchar_t>{L'\u2190',
L'\u2191', L'\u2192', L'\u2193'});
message->Body += Environment::NewLine + someArrows;
message->BodyEncoding = System::Text::Encoding::UTF8;
message->Subject = "test message 1" + someArrows;
message->SubjectEncoding = System::Text::Encoding::UTF8;
// Set the method that is called back when the send
// operation ends.
client->SendCompleted += gcnew
SendCompletedEventHandler(SendCompletedCallback);
// The userState can be any object that allows your
// callback method to identify this send operation.
// For this example, the userToken is a string constant.
String^ userState = "test message1";
client->SendAsync(message, userState);
Console::WriteLine("Sending message... press c to" +
" cancel mail. Press any other key to exit.");
String^ answer = Console::ReadLine();
// If the user canceled the send, and mail hasn't been
// sent yet,then cancel the pending operation.
if (answer->ToLower()->StartsWith("c") && mailSent == false)
{
client->SendAsyncCancel();
}
// Clean up.
delete message;
client = nullptr;
Console::WriteLine("Goodbye.");
}
else
{
Console::WriteLine("Please give SMTP server name!");
}
}
System..::.Object
System.Net.Mail..::.SmtpClient
這個型別的任何 Public static (在 Visual Basic 中為 Shared) 成員都具備執行緒安全。並非所有的執行個體成員都是安全執行緒。
Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98
.NET Framework 和 .NET Compact Framework 並不支援各種平台的所有版本。如需支援平台版本的相關資訊,請參閱 .NET Framework 系統需求。
.NET Framework
支援版本:3.5、3.0、2.0
參考