Aracılığıyla paylaş


SmtpClient.SendAsync Yöntem

Tanım

E-posta iletisi gönderir. Bu yöntemler çağıran iş parçacığını engellemez.

Aşırı Yüklemeler

SendAsync(MailMessage, Object)

Belirtilen e-posta iletisini teslim için bir SMTP sunucusuna gönderir. Bu yöntem çağıran iş parçacığını engellemez ve çağıranın işlem tamamlandığında çağrılan yönteme bir nesnesi geçirmesine izin verir.

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

Teslim için smtp sunucusuna bir e-posta iletisi gönderir. İletiyi gönderen, alıcılar, konu ve ileti gövdesi nesneler kullanılarak String belirtilir. Bu yöntem çağıran iş parçacığını engellemez ve çağıranın işlem tamamlandığında çağrılan yönteme bir nesnesi geçirmesine izin verir.

SendAsync(MailMessage, Object)

Kaynak:
SmtpClient.cs
Kaynak:
SmtpClient.cs
Kaynak:
SmtpClient.cs

Belirtilen e-posta iletisini teslim için bir SMTP sunucusuna gönderir. Bu yöntem çağıran iş parçacığını engellemez ve çağıranın işlem tamamlandığında çağrılan yönteme bir nesnesi geçirmesine izin verir.

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)

Parametreler

message
MailMessage

MailMessage Gönderilecek iletiyi içeren bir.

userToken
Object

Zaman uyumsuz işlem tamamlandığında çağrılan yöntemine geçirilen kullanıcı tanımlı nesne.

Özel durumlar

message, null değeridir.

-veya-

From, null değeridir.

Bu SmtpClient işlem zaten devam eden başka bir gönderme işlemine sahip.

-veya-

, CCve Bcc özelliklerinde Tobelirtilen alıcı yok.

-veya-

DeliveryMethod özelliği olarak Network ayarlanır ve Host şeklindedir null.

-veya-

DeliveryMethod özelliği olarak Network ayarlanır ve Host boş dizeye ("") eşittir.

-veya-

DeliveryMethod özelliği sıfır, negatif bir sayı veya 65.535'ten büyük olarak ayarlanır NetworkPort .

Bu nesne atılmış.

SMTP sunucusuyla bağlantı başarısız oldu.

-veya-

Kimlik doğrulaması gerçekleştirilemedi.

-veya-

İşlem zaman aşımına uğradı.

-veya-

EnableSslolarak ayarlanırtrue, ancak DeliveryMethod özelliği veya PickupDirectoryFromIisolarak SpecifiedPickupDirectory ayarlanır.

-veya-

EnableSsl olarak ayarlanır true, ancak SMTP posta sunucusu, EHLO komutuna yanıt olarak STARTTLS'yi tanıtmadı.

-veya-

, messageCCveya Bcciçindeki Tobir veya daha fazla alıcıya teslim edilemedi.

message, CCveya Bcciçindeki Toalıcılardan birine teslim edilemedi.

message, CCveya Bcciçindeki Toiki veya daha fazla alıcıya teslim edilemedi.

Örnekler

Aşağıdaki kod örneğinde bu yöntemin çağrılması gösterilmektedir.

#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

Açıklamalar

E-posta gönderildiğinde veya işlem iptal edildiğinde bildirim almak için SendCompleted olaya bir olay işleyicisi ekleyin. yöntemini çağırarak SendAsyncCancel işlemi SendAsync iptal edebilirsiniz.

çağrısı SendAsyncyaptıktan sonra veya SendAsynckullanarak Send başka bir e-posta iletisi göndermeye çalışmadan önce e-posta iletiminin tamamlanmasını beklemeniz gerekir.

Bu yöntemi çağırmadan önce vePort, Host ilgili özellikleri ayarlayarak veya bu bilgileri oluşturucuya SmtpClient(String, Int32) geçirerek yapılandırma dosyaları aracılığıyla ayarlanmalıdır.

SMTP konağı kimlik bilgileri gerektiriyorsa, bu yöntemi çağırmadan önce bunları ayarlamanız gerekir. Kimlik bilgilerini belirtmek için veya Credentials özelliklerini kullanınUseDefaultCredentials.

Özel durum SmtpException alırsanız, işlemin başarısız olma nedenini bulmak için özelliğini denetleyin StatusCode . , SmtpException işlemin başarısız olma nedenini gösteren bir iç özel durum da içerebilir.

kullanarak SendAsync birden çok alıcıya e-posta gönderirken, SMTP sunucusu bazı alıcıları geçerli olarak kabul ederse ve diğerlerini reddederse, SmtpException iç özel durum için ile bir NullReferenceException oluşturulur. Bu durumda alıcılardan SendAsync herhangi birine e-posta gönderemez.

Uygulamanız, temsilciye SendCompletedEventHandler geçirilen özelliği inceleyerek Error bir sunucu sertifikası doğrulama hatası algılayabilir.

özelliğinin Timeout bir çağrı üzerinde herhangi bir SendAsync etkisi yoktur.

SMTP sunucusuna iletilirken posta ve blok göndermek için yöntemlerden birini Send kullanın.

Not

EnableSsl özelliği olarak trueayarlanırsa ve SMTP posta sunucusu EHLO komutuna yanıt olarak STARTTLS'yi tanıtmazsa, veya SendAsync yöntemlerine Send yapılan bir çağrı bir SmtpExceptionoluşturur.

Şunlara uygulanır

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

Kaynak:
SmtpClient.cs
Kaynak:
SmtpClient.cs
Kaynak:
SmtpClient.cs

Teslim için smtp sunucusuna bir e-posta iletisi gönderir. İletiyi gönderen, alıcılar, konu ve ileti gövdesi nesneler kullanılarak String belirtilir. Bu yöntem çağıran iş parçacığını engellemez ve çağıranın işlem tamamlandığında çağrılan yönteme bir nesnesi geçirmesine izin verir.

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)

Parametreler

from
String

String İletiyi gönderenin adres bilgilerini içeren bir.

recipients
String

String İletinin gönderildiği adresi içeren bir.

subject
String

String İletinin konu satırını içeren bir.

body
String

String İleti gövdesini içeren bir.

userToken
Object

Zaman uyumsuz işlem tamamlandığında çağrılan yöntemine geçirilen kullanıcı tanımlı nesne.

Özel durumlar

from, null değeridir.

-veya-

recipient, null değeridir.

from, Empty değeridir.

-veya-

recipient, Empty değeridir.

Devam SmtpClient eden bir SendAsync çağrı var.

-veya-

DeliveryMethod özelliği olarak Network ayarlanır ve Host şeklindedir null.

-veya-

DeliveryMethod özelliği olarak Network ayarlanır ve Host boş dizeye ("") eşittir.

-veya-

DeliveryMethod özelliği sıfır, negatif bir sayı veya 65.535'ten büyük olarak ayarlanır NetworkPort .

Bu nesne atılmış.

SMTP sunucusuyla bağlantı başarısız oldu.

-veya-

Kimlik doğrulaması gerçekleştirilemedi.

-veya-

İşlem zaman aşımına uğradı.

-veya-

EnableSslolarak ayarlanırtrue, ancak DeliveryMethod özelliği veya PickupDirectoryFromIisolarak SpecifiedPickupDirectory ayarlanır.

-veya-

EnableSsl olarak ayarlanır true, ancak SMTP posta sunucusu, EHLO komutuna yanıt olarak STARTTLS'yi tanıtmadı.

-veya-

İleti içindeki bir veya daha fazla alıcıya recipientsteslim edilemedi.

message, CCveya Bcciçindeki Toalıcılardan birine teslim edilemedi.

message, CCveya Bcciçindeki Toiki veya daha fazla alıcıya teslim edilemedi.

Açıklamalar

E-posta gönderildiğinde veya işlem iptal edildiğinde bildirim almak için SendCompleted olaya bir olay işleyicisi ekleyin. yöntemini çağırarak SendAsyncCancel işlemi SendAsync iptal edebilirsiniz.

çağrısı SendAsyncyaptıktan sonra veya SendAsynckullanarak Send başka bir e-posta iletisi göndermeye çalışmadan önce e-posta iletiminin tamamlanmasını beklemeniz gerekir.

Bu yöntemi çağırmadan önce ve Port özellikleri yapılandırma Host dosyaları aracılığıyla veya özellikleri ayarlanarak ya da bu bilgiler oluşturucuya SmtpClient(String, Int32) geçirilerek ayarlanmalıdır.

SMTP konağı kimlik bilgileri gerektiriyorsa, bu yöntemi çağırmadan önce bunları ayarlamanız gerekir. Kimlik bilgilerini belirtmek için veya Credentials özelliğini kullanınUseDefaultCredentials.

Özel durum SmtpException alırsanız, işlemin başarısız olma nedenini bulmak için özelliğini denetleyin StatusCode . ayrıca SmtpException , işlemin başarısız olma nedenini gösteren bir iç özel durum da içerebilir.

kullanarak SendAsync birden çok alıcıya e-posta gönderirken, SMTP sunucusu bazı alıcıları geçerli olarak kabul ederse ve diğerlerini reddederse, SmtpException iç özel durum için ile bir NullReferenceException oluşturulur. Bu durumda alıcılardan SendAsync herhangi birine e-posta gönderemezsiniz.

Uygulamanız, temsilciye SendCompletedEventHandler geçirilen özelliği inceleyerek Error bir sunucu sertifikası doğrulama hatası algılayabilir.

özelliğinin Timeout bir çağrı üzerinde herhangi bir SendAsync etkisi yoktur.

SMTP sunucusuna iletilirken posta ve blok göndermek için yöntemlerden birini Send kullanın.

Not

EnableSsl özelliği olarak trueayarlanırsa ve SMTP posta sunucusu EHLO komutuna yanıt olarak STARTTLS'yi tanıtmazsa, veya SendAsync yöntemlerine Send yönelik bir çağrı oluşturulurSmtpException.

Şunlara uygulanır