SmtpClient クラス
定義
重要
一部の情報は、リリース前に大きく変更される可能性があるプレリリースされた製品に関するものです。 Microsoft は、ここに記載されている情報について、明示または黙示を問わず、一切保証しません。
注意事項
SmtpClient and its network of types are poorly designed, we strongly recommend you use https://github.com/jstedfast/MailKit and https://github.com/jstedfast/MimeKit instead
アプリケーションが SMTP (簡易メール転送プロトコル) を使用して電子メールを送信できるようにします。 型は SmtpClient 一部のプラットフォームでは廃止されており、他のプラットフォームでは推奨されません。詳細については、「解説」セクションを参照してください。
public ref class SmtpClient : IDisposable
public ref class SmtpClient
public class SmtpClient : IDisposable
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public class SmtpClient : IDisposable
public class SmtpClient
[System.Obsolete("SmtpClient and its network of types are poorly designed, we strongly recommend you use https://github.com/jstedfast/MailKit and https://github.com/jstedfast/MimeKit instead")]
public class SmtpClient : IDisposable
type SmtpClient = class
interface IDisposable
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
type SmtpClient = class
interface IDisposable
type SmtpClient = class
[<System.Obsolete("SmtpClient and its network of types are poorly designed, we strongly recommend you use https://github.com/jstedfast/MailKit and https://github.com/jstedfast/MimeKit instead")>]
type SmtpClient = class
interface IDisposable
Public Class SmtpClient
Implements IDisposable
Public Class SmtpClient
- 継承
-
SmtpClient
- 属性
- 実装
例
次のコード例は、電子メール メッセージを非同期に送信する方法を示しています。
#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 be the SMTP host.
SmtpClient^ client = gcnew SmtpClient(args[1]);
// Specify the email 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 email message.
MailAddress^ to = gcnew MailAddress("ben@contoso.com");
// Specify the message content.
MailMessage^ message = gcnew MailMessage(from, to);
message->Body = "This is a test email 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!");
}
}
using System;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading;
using System.ComponentModel;
namespace Examples.SmtpExamples.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 be the SMTP host.
SmtpClient client = new SmtpClient(args[0]);
// Specify the email 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 email message.
MailAddress to = new MailAddress("ben@contoso.com");
// Specify the message content.
MailMessage message = new MailMessage(from, to);
message.Body = "This is a test email 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.");
}
}
}
Imports System.Net
Imports System.Net.Mail
Imports System.Net.Mime
Imports System.Threading
Imports System.ComponentModel
Namespace Examples.SmtpExamples.Async
Public Class SimpleAsynchronousExample
Private Shared mailSent As Boolean = False
Private Shared Sub SendCompletedCallback(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs)
' Get the unique identifier for this asynchronous operation.
Dim token As String = CStr(e.UserState)
If e.Cancelled Then
Console.WriteLine("[{0}] Send canceled.", token)
End If
If e.Error IsNot Nothing Then
Console.WriteLine("[{0}] {1}", token, e.Error.ToString())
Else
Console.WriteLine("Message sent.")
End If
mailSent = True
End Sub
Public Shared Sub Main(ByVal args() As String)
' Command line argument must the SMTP host.
Dim client As New SmtpClient(args(0))
' Specify the email sender.
' Create a mailing address that includes a UTF8 character
' in the display name.
Dim mailFrom As New MailAddress("jane@contoso.com", "Jane " & ChrW(&HD8) & " Clayton", System.Text.Encoding.UTF8)
' Set destinations for the email message.
Dim mailTo As New MailAddress("ben@contoso.com")
' Specify the message content.
Dim message As New MailMessage(mailFrom, mailTo)
message.Body = "This is a test email message sent by an application. "
' Include some non-ASCII characters in body and subject.
Dim someArrows As New String(New Char() {ChrW(&H2190), ChrW(&H2191), ChrW(&H2192), ChrW(&H2193)})
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.
AddHandler client.SendCompleted, AddressOf 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.
Dim userState As String = "test message1"
client.SendAsync(message, userState)
Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.")
Dim answer As String = Console.ReadLine()
' If the user canceled the send, and mail hasn't been sent yet,
' then cancel the pending operation.
If answer.StartsWith("c") AndAlso mailSent = False Then
client.SendAsyncCancel()
End If
' Clean up.
message.Dispose()
Console.WriteLine("Goodbye.")
End Sub
End Class
End Namespace
注釈
クラスは SmtpClient
、配信のために SMTP サーバーに電子メールを送信するために使用されます。 SMTP プロトコルは RFC 2821 で定義されています。これは で https://www.ietf.org使用できます。
重要
多くの最新のプロトコルをサポートしていないためSmtpClient
、SmtpClient
新しい開発には クラスを使用しないことをお勧めします。 代わりに MailKit またはその他のライブラリを使用してください。 詳細については、「 SmtpClient を GitHub で使用しないでください」を参照してください。
クラスは SmtpClient
Xamarin では廃止されています。 ただし
- これは .NET Standard 2.0 以降のバージョンに含まれているため、これらのバージョンをサポートする .NET 実装の一部である必要があります。
- これは存在し、.NET Framework 4 ~ .NET Framework 4.8 で使用できます。
- .NET Core では使用できますが、その使用はお勧めしません。
次の表に示すクラスは、 を使用して送信できる電子メール メッセージを作成するために使用 SmtpClientされます。
クラス | 説明 |
---|---|
Attachment | 添付ファイルを表します。 このクラスを使用すると、ファイル、ストリーム、またはテキストをメール メッセージに添付できます。 |
MailAddress | 送信者と受信者のメール アドレスを表します。 |
MailMessage | 電子メール メッセージを表します。 |
を使用 SmtpClientして電子メール メッセージを作成して送信するには、次の情報を指定する必要があります。
SMTP サーバーで必要な場合は、認証の資格情報。 Credentials プロパティをご覧ください。
送信者の電子メール アドレス。 パラメーターを Send 受け取る メソッドと SendAsync メソッドを
from
参照してください。 プロパティも参照してください MailMessage.From 。受信者のメール アドレスまたはアドレス。 パラメーターを Send 受け取る メソッドと SendAsync メソッドを
recipient
参照してください。 プロパティも参照してください MailMessage.To 。メッセージのコンテンツ。 パラメーターを Send 受け取る メソッドと SendAsync メソッドを
body
参照してください。 プロパティも参照してください MailMessage.Body 。
電子メール メッセージに添付ファイルを含めるには、まず クラスを使用して添付ファイルを Attachment 作成し、 プロパティを使用 MailMessage.Attachments してメッセージに追加します。 受信者が使用するメール リーダーと添付ファイルの種類によっては、一部の受信者が添付ファイルを読み取ることができない場合があります。 元の形式で添付ファイルを表示できないクライアントの場合は、 プロパティを使用して代替ビューを MailMessage.AlternateViews 指定できます。
.NET Frameworkでは、アプリケーションまたはマシン構成ファイルを使用して、すべてのSmtpClientオブジェクトの既定のホスト、ポート、資格情報の値を指定できます。 詳細については、「mailSettings> 要素 (ネットワーク設定)」を参照してください<。 .NET Core では、既定値の設定はサポートされていません。 回避策として、関連するプロパティを 直接 に設定する SmtpClient 必要があります。
SMTP サーバーに電子メールが送信されるのを待っている間に電子メール メッセージを送信してブロックするには、同期 Send メソッドのいずれかを使用します。 電子メールの送信中にプログラムのメイン スレッドの実行を続行できるようにするには、非同期SendAsyncメソッドのいずれかを使用します。 イベントは SendCompleted 、操作の完了時に SendAsync 発生します。 このイベントを受信するには、 にデリゲートを SendCompletedEventHandler 追加する SendCompleted必要があります。 デリゲートは SendCompletedEventHandler 、イベントの通知を処理するコールバック メソッドを SendCompleted 参照する必要があります。 非同期の電子メール送信を取り消すには、 メソッドを使用します SendAsyncCancel 。
注意
メール送信が進行中で、 または Send を再度呼び出SendAsyncすと、 が表示InvalidOperationExceptionされます。
アプリケーションが同じ SMTP サーバーに複数のメッセージを SmtpClient 送信する場合は、 クラスの現在のインスタンスによって SMTP サーバーへの接続が確立された接続を再利用できます。 これは、認証または暗号化を使用して SMTP サーバーへの接続を確立する場合に特に便利です。 TLS セッションを認証して確立するプロセスは、コストのかかる操作になる可能性があります。 同じ SMTP サーバーに大量の電子メールを送信するときに、各メッセージの接続を再確立する必要があると、パフォーマンスに大きな影響を与える可能性があります。 電子メールの状態の更新、ニュースレターの配布、または電子メールアラートを送信する大量の電子メール アプリケーションが多数あります。 また、多くの電子メール クライアント アプリケーションでは、SMTP サーバーへの接続が確立されたときに後で送信される多くの電子メール メッセージをユーザーが作成できるオフライン モードがサポートされています。 電子メール クライアントでは、(インターネット サービス プロバイダーによって提供される) 特定の SMTP サーバーにすべての SMTP メッセージを送信し、この電子メールを他の SMTP サーバーに転送するのが一般的です。
クラス実装では SmtpClient SMTP 接続がプールされるため、同じサーバーへのすべてのメッセージの接続を再確立するオーバーヘッドを回避できます。 アプリケーションは、同じオブジェクトを再利用して、同じ SmtpClient SMTP サーバーとさまざまな SMTP サーバーに多数の異なる電子メールを送信できます。 その結果、 オブジェクトを使用してアプリケーションがいつ終了し、クリーンアップする必要があるかを SmtpClient 判断する方法はありません。
SMTP セッションが終了し、クライアントが接続を終了する場合は、サーバーに QUIT メッセージを送信して、送信するメッセージがないことを示す必要があります。 これにより、サーバーはクライアントから接続に関連付けられているリソースを解放し、クライアントによって送信されたメッセージを処理できます。
クラスには SmtpClient メソッドがないため Finalize
、アプリケーションで を呼び出 Dispose してリソースを明示的に解放する必要があります。 メソッドは Dispose 、 プロパティで指定された SMTP サーバーへの確立されたすべての接続を Host 反復処理し、QUIT メッセージを送信し、その後に TCP 接続を正常に終了します。 メソッドは Dispose 、 によって Socket 使用されるアンマネージ リソースも解放し、必要に応じてマネージド リソースを破棄します。
Dispose を使い終わったら SmtpClient を呼び出します。 Disposeメソッドによって、SmtpClient は使用不可の状態になります。 Dispose呼び出し後は、SmtpClientによって占有されていたメモリをガベージ コレクターがクリアできるよう、SmtpClient へのすべての参照を解放する必要があります。
コンストラクター
SmtpClient() |
互換性のために残されています。
構成ファイルの設定を使用して SmtpClient クラスの新しいインスタンスを初期化します。 |
SmtpClient(String) |
互換性のために残されています。
指定した SMTP サーバーを使用して電子メールを送信する SmtpClient クラスの新しいインスタンスを初期化します。 |
SmtpClient(String, Int32) |
互換性のために残されています。
指定した SMTP サーバーとポートを使用して電子メールを送信する SmtpClient クラスのインスタンスを初期化します。 |
プロパティ
ClientCertificates |
互換性のために残されています。
SSL (Secure Sockets Layer) 接続を確立するために使用する必要のある証明書を指定します。 |
Credentials |
互換性のために残されています。
差出人の認証に使用する資格情報を取得または設定します。 |
DeliveryFormat |
互換性のために残されています。
電子メールを送信するために SmtpClient によって使用される配信形式を取得または設定します。 |
DeliveryMethod |
互換性のために残されています。
送信メッセージの処理方法を指定します。 |
EnableSsl |
互換性のために残されています。
SmtpClient が、接続を暗号化するために SSL (Secure Sockets Layer) を使用するかどうかを指定します。 |
Host |
互換性のために残されています。
SMTP トランザクションで使用されるホストの名前または IP アドレスを取得または設定します。 |
PickupDirectoryLocation |
互換性のために残されています。
ローカルの SMTP サーバーによって処理される電子メール メッセージをアプリケーションが保存するフォルダーを取得または設定します。 |
Port |
互換性のために残されています。
SMTP トランザクションで使用されるポートを取得または設定します。 |
ServicePoint |
互換性のために残されています。
電子メール メッセージの送信に使用するネットワーク接続を取得します。 |
TargetName |
互換性のために残されています。
拡張保護を使用するときの認証に使用するサービス プロバイダー名 (SPN: Service Provider Name) を取得または設定します。 |
Timeout |
互換性のために残されています。
同期的な Send 呼び出しがタイムアウトになるまでの時間を指定する値を取得または設定します。 |
UseDefaultCredentials |
互換性のために残されています。
Boolean が要求と共に送信されるかどうかを制御する DefaultCredentials 値を取得または設定します。 |
メソッド
Dispose() |
互換性のために残されています。
QUIT メッセージを SMTP サーバーに送信し、TCP 接続を適切に終了して、SmtpClient クラスの現在のインスタンスで使用されているすべてのリソースを解放します。 |
Dispose(Boolean) |
互換性のために残されています。
QUIT メッセージを SMTP サーバーに送信し、TCP 接続を適切に終了して、SmtpClient クラスの現在のインスタンスで使用されているすべてのリソースを解放します。オプションでマネージド リソースも破棄します。 |
Equals(Object) |
互換性のために残されています。
指定されたオブジェクトが現在のオブジェクトと等しいかどうかを判断します。 (継承元 Object) |
GetHashCode() |
互換性のために残されています。
既定のハッシュ関数として機能します。 (継承元 Object) |
GetType() |
互換性のために残されています。
現在のインスタンスの Type を取得します。 (継承元 Object) |
MemberwiseClone() |
互換性のために残されています。
現在の Object の簡易コピーを作成します。 (継承元 Object) |
OnSendCompleted(AsyncCompletedEventArgs) |
互換性のために残されています。
SendCompleted イベントを発生させます。 |
Send(MailMessage) |
互換性のために残されています。
指定したメッセージを、配信用 SMTP サーバーに送信します。 |
Send(String, String, String, String) |
互換性のために残されています。
指定した電子メール メッセージを、配信用 SMTP サーバーに送信します。 メッセージの差出人、受信者、件名、およびメッセージ本文は、String オブジェクトを使用して指定されます。 |
SendAsync(MailMessage, Object) |
互換性のために残されています。
指定した電子メール メッセージを、配信用 SMTP サーバーに送信します。 このメソッドは、呼び出し元のスレッドをブロックしません。また、呼び出し元は、操作の完了時に呼び出されるメソッドにオブジェクトを渡すことができます。 |
SendAsync(String, String, String, String, Object) |
互換性のために残されています。
電子メール メッセージを、配信用 SMTP サーバーに送信します。 メッセージの差出人、受信者、件名、およびメッセージ本文は、String オブジェクトを使用して指定されます。 このメソッドは、呼び出し元のスレッドをブロックしません。また、呼び出し元は、操作の完了時に呼び出されるメソッドにオブジェクトを渡すことができます。 |
SendAsyncCancel() |
互換性のために残されています。
電子メール メッセージを送信する非同期操作をキャンセルします。 |
SendMailAsync(MailMessage) |
互換性のために残されています。
非同期操作として、指定したメッセージを配信用 SMTP サーバーに送信します。 |
SendMailAsync(MailMessage, CancellationToken) |
互換性のために残されています。
非同期操作として、指定したメッセージを配信用 SMTP サーバーに送信します。 |
SendMailAsync(String, String, String, String) |
互換性のために残されています。
非同期操作として、指定したメッセージを配信用 SMTP サーバーに送信します。 メッセージの差出人、受信者、件名、およびメッセージ本文は、String オブジェクトを使用して指定されます。 |
SendMailAsync(String, String, String, String, CancellationToken) |
互換性のために残されています。
指定された差出人、受信者、件名、本文の文字列を使用し、非同期操作として、指定されたメッセージを配信のために SMTP サーバーに送信します。 |
ToString() |
互換性のために残されています。
現在のオブジェクトを表す文字列を返します。 (継承元 Object) |
events
SendCompleted |
互換性のために残されています。
電子メールの非同期的な送信操作が完了した場合に発生します。 |