SmtpClient.SendAsync 메서드

정의

이메일 메시지를 보냅니다. 이들 메서드는 호출 스레드를 차단하지 않습니다.

오버로드

SendAsync(MailMessage, Object)

배달용 SMTP 서버로 지정된 이메일 메시지를 보냅니다. 이 메서드는 호출 스레드를 차단하지 않으며 작업이 완료될 때 호출된 메서드에 호출자가 개체를 전달하도록 허용합니다.

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

배달용 SMTP 서버로 이메일 메시지를 보냅니다. 메시지의 보낸 사람, 받는 사람, 제목 및 메시지 본문은 String 개체를 사용하여 지정됩니다. 이 메서드는 호출 스레드를 차단하지 않으며 작업이 완료될 때 호출된 메서드에 호출자가 개체를 전달하도록 허용합니다.

SendAsync(MailMessage, Object)

Source:
SmtpClient.cs
Source:
SmtpClient.cs
Source:
SmtpClient.cs

배달용 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

비동기 작업이 완료될 때 호출되는 메서드로 전달되는 사용자 정의 개체입니다.

예외

message이(가) null인 경우

또는

Fromnull입니다.

이미 SmtpClient 진행 중인 다른 보내기 작업이 있습니다.

또는

To, CCBcc 속성에 지정된 받는 사람이 없습니다.

또는

DeliveryMethod 속성은 Network로 설정되고 Hostnull입니다.

또는

DeliveryMethod 속성이 Network로 설정되고 Host가 빈 문자열("")과 같습니다.

또는

DeliveryMethod 속성은 Network로 설정되고 Port는 0, 음수 또는 65,535보다 큽니다.

이 개체가 삭제되었습니다.

SMTP 서버에 연결하지 못했습니다.

또는

인증에 실패했습니다.

또는

작업 시간이 초과되었습니다.

또는

EnableSsltrue로 설정되지만 DeliveryMethod 속성은 SpecifiedPickupDirectory 또는 PickupDirectoryFromIis로 설정됩니다.

또는

EnableSsltrue,로 설정되지만 SMTP 메일 서버는 응답에서 STARTTLS를 EHLO 명령에 알리지 않았습니다.

또는

To, CC 또는 Bcc에 있는 한 명 이상의 받는 사람에게 message를 배달하지 못한 경우

To, CC 또는 Bcc에 있는 받는 사람 중 한 명에게 message를 배달하지 못한 경우

To, CC 또는 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 호출하기 전에 관련 속성을 설정하거나 이 정보를 생성자에 전달하여 구성 파일을 통해 및 PortSmtpClient(String, Int32) 설정해야 합니다.

SMTP 호스트에 자격 증명이 필요한 경우 이 메서드를 호출하기 전에 설정해야 합니다. 자격 증명을 지정하려면 또는 Credentials 속성을 사용합니다UseDefaultCredentials.

예외가 SmtpException 표시되면 속성을 검사 StatusCode 작업이 실패한 이유를 찾습니다. 에는 SmtpException 작업이 실패한 이유를 나타내는 내부 예외도 포함될 수 있습니다.

를 사용하여 SendAsync 여러 받는 사람에게 전자 메일을 보낼 때 SMTP 서버가 일부 받는 사람을 유효한 것으로 수락하고 다른 SmtpException 받는 사람을 거부하는 경우 내부 예외에 대해 가 NullReferenceException throw됩니다. 이 경우 SendAsync 받는 사람에게 전자 메일을 보내지 못합니다.

애플리케이션을 검사 하 여 서버 인증서 유효성 검사 오류를 감지할 수 있습니다 합니다 Error 속성에 전달 합니다 SendCompletedEventHandler 대리자입니다.

속성은 Timeout 호출에 SendAsync 영향을 주지 않습니다.

메일을 보내고 SMTP 서버로 전송되는 동안 차단하려면 메서드 중 Send 하나를 사용합니다.

참고

속성이 EnableSsl 로 설정true되고 SMTP 메일 서버가 EHLO 명령에 대한 응답으로 STARTTLS를 보급하지 않는 경우 또는 SendAsync 메서드를 Send 호출하면 가 SmtpExceptionthrow됩니다.

적용 대상

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

Source:
SmtpClient.cs
Source:
SmtpClient.cs
Source:
SmtpClient.cs

배달용 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입니다.

또는

recipient이(가) null인 경우

from이(가) Empty인 경우

또는

recipient이(가) Empty인 경우

SmtpClient에서 SendAsync 호출이 진행 중인 경우

또는

DeliveryMethod 속성은 Network로 설정되고 Hostnull입니다.

또는

DeliveryMethod 속성이 Network로 설정되고 Host가 빈 문자열("")과 같습니다.

또는

DeliveryMethod 속성은 Network로 설정되고 Port는 0, 음수 또는 65,535보다 큽니다.

이 개체가 삭제되었습니다.

SMTP 서버에 연결하지 못했습니다.

또는

인증에 실패했습니다.

또는

작업 시간이 초과되었습니다.

또는

EnableSsltrue로 설정되지만 DeliveryMethod 속성은 SpecifiedPickupDirectory 또는 PickupDirectoryFromIis로 설정됩니다.

또는

EnableSsltrue,로 설정되지만 SMTP 메일 서버는 응답에서 STARTTLS를 EHLO 명령에 알리지 않았습니다.

또는

recipients에 있는 한 명 이상의 받는 사람에게 메시지를 배달하지 못한 경우

To, CC 또는 Bcc에 있는 받는 사람 중 한 명에게 message를 배달하지 못한 경우

To, CC 또는 Bcc에 있는 두 명 이상의 받는 사람에게 message를 배달하지 못한 경우

설명

전자 메일이 전송되었거나 작업이 취소된 경우 알림을 받으려면 이벤트에 이벤트 처리기를 SendCompleted 추가합니다. 메서드를 SendAsync 호출하여 작업을 취소할 SendAsyncCancel 수 있습니다.

를 호출SendAsync한 후 또는 SendAsync을 사용하여 Send 다른 전자 메일 메시지를 보내기 전에 전자 메일 전송이 완료되기를 기다려야 합니다.

이 메서드를 Host 호출하기 전에 구성 파일을 통해 또는 속성을 설정하거나 이 정보를 SmtpClient(String, Int32) 생성자에 전달하여 및 Port 속성을 설정해야 합니다.

SMTP 호스트에 자격 증명이 필요한 경우 이 메서드를 호출하기 전에 설정해야 합니다. 자격 증명을 지정하려면 또는 Credentials 속성을 사용합니다UseDefaultCredentials.

예외가 SmtpException 표시되면 속성을 검사 StatusCode 작업이 실패한 이유를 찾습니다. 에는 SmtpException 작업이 실패한 이유를 나타내는 내부 예외도 포함될 수 있습니다.

를 사용하여 SendAsync 여러 받는 사람에게 전자 메일을 보낼 때 SMTP 서버가 일부 받는 사람을 유효한 것으로 수락하고 다른 SmtpException 받는 사람을 거부하는 경우 내부 예외에 대해 가 NullReferenceException throw됩니다. 이 경우 SendAsync 받는 사람에게 전자 메일을 보내지 못합니다.

애플리케이션을 검사 하 여 서버 인증서 유효성 검사 오류를 감지할 수 있습니다 합니다 Error 속성에 전달 합니다 SendCompletedEventHandler 대리자입니다.

속성은 Timeout 호출에 SendAsync 영향을 주지 않습니다.

메일을 보내고 SMTP 서버로 전송되는 동안 차단하려면 메서드 중 Send 하나를 사용합니다.

참고

속성이 EnableSsl 로 설정true되고 SMTP 메일 서버가 EHLO 명령에 대한 응답으로 STARTTLS를 보급하지 않는 경우 또는 SendAsync 메서드를 Send 호출하면 가 SmtpExceptionthrow됩니다.

적용 대상