SmtpClient.SendAsync メソッド

定義

電子メールを送信します。 これらのメソッドは、呼び出し元のスレッドをブロックしません。

オーバーロード

SendAsync(MailMessage, Object)

指定した電子メール メッセージを、配信用 SMTP サーバーに送信します。 このメソッドは、呼び出し元のスレッドをブロックしません。また、呼び出し元は、操作の完了時に呼び出されるメソッドにオブジェクトを渡すことができます。

SendAsync(String, String, String, String, Object)

電子メール メッセージを、配信用 SMTP サーバーに送信します。 メッセージの差出人、受信者、件名、およびメッセージ本文は、String オブジェクトを使用して指定されます。 このメソッドは、呼び出し元のスレッドをブロックしません。また、呼び出し元は、操作の完了時に呼び出されるメソッドにオブジェクトを渡すことができます。

SendAsync(MailMessage, Object)

指定した電子メール メッセージを、配信用 SMTP サーバーに送信します。 このメソッドは、呼び出し元のスレッドをブロックしません。また、呼び出し元は、操作の完了時に呼び出されるメソッドにオブジェクトを渡すことができます。

public:
 void SendAsync(System::Net::Mail::MailMessage ^ message, System::Object ^ userToken);
public void SendAsync (System.Net.Mail.MailMessage message, object? userToken);
public void SendAsync (System.Net.Mail.MailMessage message, object userToken);
member this.SendAsync : System.Net.Mail.MailMessage * obj -> unit
Public Sub SendAsync (message As MailMessage, userToken As Object)

パラメーター

message
MailMessage

送信するメッセージを格納した MailMessage

userToken
Object

非同期操作の完了時に呼び出されるメソッドに渡されるユーザー定義のオブジェクト。

例外

messagenullです。

または

Fromnull です。

これには SmtpClient 、既に別の送信操作が進行中です。

- または -

ToCC、および Bcc の各プロパティで受信者が指定されていません。

- または -

DeliveryMethod プロパティは Network に設定され、Hostnull です。

- または -

DeliveryMethod プロパティは Network に設定され、Host は空の文字列 ("") と等しくなります。

- または -

DeliveryMethod プロパティが Network に設定され、Port がゼロ、負の値、または 65,535 より大きい値になっています。

このオブジェクトは破棄されました。

SMTP サーバーへの接続に失敗しました。

- または -

認証に失敗しました。

- または -

操作はタイムアウトしました。

- または -

EnableSsltrue に設定されますが、DeliveryMethod プロパティは SpecifiedPickupDirectory または PickupDirectoryFromIis に設定されます。

- または -

EnableSsltrue, に設定されていますが、SMTP メール サーバーが EHLO コマンドに対する応答で STARTTLS をアドバタイズしませんでした。

- または -

ToCC、または Bcc 内の 1 人以上の受信者に、message を配信できませんでした。

ToCC、または Bcc 内の 1 人の受信者に、message を配信できませんでした。

ToCC、または Bcc 内の複数の受信者に、message を配信できませんでした。

次のコード例は、このメソッドの呼び出しを示しています。

#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

注釈

メールが送信されたとき、または操作が取り消されたときに通知を受信するには、イベント ハンドラーをイベントに SendCompleted 追加します。 メソッドを SendAsync 呼び出すことで、操作を SendAsyncCancel 取り消すことができます。

を呼び出したSendAsync後、 または SendAsyncを使用してSend別の電子メール メッセージを送信する前に、メール送信が完了するまで待機する必要があります。

このメソッドを呼び出す前に Host 、関連するプロパティを設定するか、この情報をコンストラクターに渡すことによって、 と Port を構成ファイルで設定する SmtpClient(String, Int32) 必要があります。

SMTP ホストに資格情報が必要な場合は、このメソッドを呼び出す前にそれらを設定する必要があります。 資格情報を指定するには、 または Credentials プロパティを使用しますUseDefaultCredentials

例外が発生したSmtpException場合は、 プロパティをStatusCodeチェックして、操作が失敗した理由を見つけます。 SmtpExceptionには、操作が失敗した理由を示す内部例外を含めることもできます。

を使用して複数の受信者に電子メールを SendAsync 送信する場合、SMTP サーバーが一部の受信者を有効として受け入れ、他の受信者を拒否した場合は、 SmtpException 内部例外の と NullReferenceException 共に がスローされます。 これが発生した場合、 SendAsync 受信者に電子メールを送信できません。

アプリケーションは、デリゲートに渡されたプロパティを調べることで、サーバー証明書の Error 検証エラーを SendCompletedEventHandler 検出できます。

プロパティは Timeout 、呼び出しには SendAsync 影響しません。

SMTP サーバーへの送信中にメールとブロックを送信するには、いずれかの方法を Send 使用します。

注意

プロパティが EnableSsltrue設定されていて、SMTP メール サーバーが EHLO コマンドへの応答で STARTTLS をアドバタイズしない場合、 メソッドまたは SendAsync メソッドのSend呼び出しで がSmtpExceptionスローされます。

適用対象

SendAsync(String, String, String, String, Object)

電子メール メッセージを、配信用 SMTP サーバーに送信します。 メッセージの差出人、受信者、件名、およびメッセージ本文は、String オブジェクトを使用して指定されます。 このメソッドは、呼び出し元のスレッドをブロックしません。また、呼び出し元は、操作の完了時に呼び出されるメソッドにオブジェクトを渡すことができます。

public:
 void SendAsync(System::String ^ from, System::String ^ recipients, System::String ^ subject, System::String ^ body, System::Object ^ userToken);
public void SendAsync (string from, string recipients, string? subject, string? body, object? userToken);
public void SendAsync (string from, string recipients, string subject, string body, object userToken);
member this.SendAsync : string * string * string * string * obj -> unit
Public Sub SendAsync (from As String, recipients As String, subject As String, body As String, userToken As Object)

パラメーター

from
String

メッセージの差出人のアドレス情報を格納している String

recipients
String

メッセージの送信先のアドレスを格納している String

subject
String

メッセージの件名を格納している String

body
String

メッセージ本文を格納している String

userToken
Object

非同期操作の完了時に呼び出されるメソッドに渡されるユーザー定義のオブジェクト。

例外

fromnull です。

または

recipientnull です。

fromEmpty です。

または

recipientEmptyです。

この SmtpClient は、SendAsync の呼び出し中です。

- または -

DeliveryMethod プロパティは Network に設定され、Hostnull です。

- または -

DeliveryMethod プロパティは Network に設定され、Host は空の文字列 ("") と等しくなります。

- または -

DeliveryMethod プロパティが Network に設定され、Port がゼロ、負の値、または 65,535 より大きい値になっています。

このオブジェクトは破棄されました。

SMTP サーバーへの接続に失敗しました。

- または -

認証に失敗しました。

- または -

操作はタイムアウトしました。

- または -

EnableSsltrue に設定されますが、DeliveryMethod プロパティは SpecifiedPickupDirectory または PickupDirectoryFromIis に設定されます。

- または -

EnableSsltrue, に設定されていますが、SMTP メール サーバーが EHLO コマンドに対する応答で STARTTLS をアドバタイズしませんでした。

- または -

recipients 内の 1 人以上の受信者に、メッセージを配信できませんでした。

ToCC、または Bcc 内の 1 人の受信者に、message を配信できませんでした。

ToCC、または Bcc 内の複数の受信者に、message を配信できませんでした。

注釈

メールが送信されたとき、または操作が取り消されたときに通知を受信するには、イベント ハンドラーをイベントに SendCompleted 追加します。 メソッドを SendAsync 呼び出すことで、操作を SendAsyncCancel 取り消すことができます。

を呼び出したSendAsync後、 または SendAsyncを使用してSend別の電子メール メッセージを送信する前に、メール送信が完了するまで待機する必要があります。

このメソッドを呼び出す前に Host 、 プロパティと Port プロパティを構成ファイルで設定するか、プロパティを設定するか、この情報をコンストラクターに SmtpClient(String, Int32) 渡す必要があります。

SMTP ホストに資格情報が必要な場合は、このメソッドを呼び出す前にそれらを設定する必要があります。 資格情報を指定するには、 または Credentials プロパティをUseDefaultCredentials使用します。

例外が発生したSmtpException場合は、 プロパティをStatusCodeチェックして、操作が失敗した理由を見つけます。 SmtpExceptionには、操作が失敗した理由を示す内部例外を含めることもできます。

を使用して複数の受信者に電子メールを SendAsync 送信するときに、SMTP サーバーが一部の受信者を有効として受け入れ、他の受信者を拒否した場合、 SmtpException 内部例外の が NullReferenceException でスローされます。 これが発生した場合、 SendAsync 受信者のいずれかにメールを送信できません。

アプリケーションは、デリゲートに渡されたプロパティを調べることで、サーバー証明書の Error 検証エラーを SendCompletedEventHandler 検出できます。

プロパティは Timeout 、呼び出しに影響 SendAsync を及ぼすことはありません。

SMTP サーバーへの送信中にメールとブロックを送信するには、いずれかの方法を Send 使用します。

注意

プロパティが EnableSsltrue設定されていて、SMTP メール サーバーが EHLO コマンドへの応答で STARTTLS をアドバタイズしない場合、 メソッドまたは SendAsync メソッドのSend呼び出しによって がSmtpExceptionスローされます。

適用対象