SmtpClient.SendAsync Method
Definition
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Sends an email message. These methods do not block the calling thread.
Overloads
SendAsync(MailMessage, Object) |
Sends the specified email message to an SMTP server for delivery. This method does not block the calling thread and allows the caller to pass an object to the method that is invoked when the operation completes. |
SendAsync(String, String, String, String, Object) |
Sends an email message to an SMTP server for delivery. The message sender, recipients, subject, and message body are specified using String objects. This method does not block the calling thread and allows the caller to pass an object to the method that is invoked when the operation completes. |
SendAsync(MailMessage, Object)
- Source:
- SmtpClient.cs
- Source:
- SmtpClient.cs
- Source:
- SmtpClient.cs
Sends the specified email message to an SMTP server for delivery. This method does not block the calling thread and allows the caller to pass an object to the method that is invoked when the operation completes.
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)
Parameters
- message
- MailMessage
A MailMessage that contains the message to send.
- userToken
- Object
A user-defined object that is passed to the method invoked when the asynchronous operation completes.
Exceptions
This SmtpClient has another send operation already in progress.
-or-
There are no recipients specified in To, CC, and Bcc properties.
-or-
DeliveryMethod property is set to Network and Host is null
.
-or-
DeliveryMethod property is set to Network and Host is equal to the empty string ("").
-or-
DeliveryMethod property is set to Network and Port is zero, a negative number, or greater than 65,535.
This object has been disposed.
The connection to the SMTP server failed.
-or-
Authentication failed.
-or-
The operation timed out.
-or-
EnableSsl is set to true
but the DeliveryMethod property is set to SpecifiedPickupDirectory or PickupDirectoryFromIis.
-or-
EnableSsl is set to true,
but the SMTP mail server did not advertise STARTTLS in the response to the EHLO command.
-or-
The message
could not be delivered to one or more of the recipients in To, CC, or Bcc.
Examples
The following code example demonstrates calling this method.
#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)
{
client->SendAsyncCancel();
}
// Clean up.
delete message;
delete client;
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)
{
client.SendAsyncCancel();
}
// Clean up.
message.Dispose();
client.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()
client.Dispose()
Console.WriteLine("Goodbye.")
End Sub
End Class
End Namespace
Remarks
To receive notification when the email has been sent or the operation has been canceled, add an event handler to the SendCompleted event. You can cancel a SendAsync operation by calling the SendAsyncCancel method.
After calling SendAsync, you must wait for the email transmission to complete before attempting to send another email message using Send or SendAsync.
Before calling this method, the Host and Port must be set through the configuration files by setting the relevant properties, or by passing this information into the SmtpClient(String, Int32) constructor.
If the SMTP host requires credentials, you must set them before calling this method. To specify credentials, use the UseDefaultCredentials or Credentials properties.
If you receive an SmtpException exception, check the StatusCode property to find the reason the operation failed. The SmtpException can also contain an inner exception that indicates the reason the operation failed.
When sending email using SendAsync to multiple recipients, if the SMTP server accepts some recipients as valid and rejects others, a SmtpException is thrown with a NullReferenceException for the inner exception. If this occurs, SendAsync fails to send email to any of the recipients.
Your application can detect a server certificate validation error by examining the Error property passed into the SendCompletedEventHandler delegate.
The Timeout property does not have any effect on a SendAsync call.
To send mail and block while it is transmitted to the SMTP server, use one of the Send methods.
Note
If the EnableSsl property is set to true
, and the SMTP mail server does not advertise STARTTLS in the response to the EHLO command, then a call to the Send or SendAsync methods will throw an SmtpException.
Applies to
SendAsync(String, String, String, String, Object)
- Source:
- SmtpClient.cs
- Source:
- SmtpClient.cs
- Source:
- SmtpClient.cs
Sends an email message to an SMTP server for delivery. The message sender, recipients, subject, and message body are specified using String objects. This method does not block the calling thread and allows the caller to pass an object to the method that is invoked when the operation completes.
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)
Parameters
- userToken
- Object
A user-defined object that is passed to the method invoked when the asynchronous operation completes.
Exceptions
This SmtpClient has a SendAsync call in progress.
-or-
DeliveryMethod property is set to Network and Host is null
.
-or-
DeliveryMethod property is set to Network and Host is equal to the empty string ("").
-or-
DeliveryMethod property is set to Network and Port is zero, a negative number, or greater than 65,535.
This object has been disposed.
The connection to the SMTP server failed.
-or-
Authentication failed.
-or-
The operation timed out.
-or-
EnableSsl is set to true
but the DeliveryMethod property is set to SpecifiedPickupDirectory or PickupDirectoryFromIis.
-or-
EnableSsl is set to true,
but the SMTP mail server did not advertise STARTTLS in the response to the EHLO command.
-or-
The message could not be delivered to one or more of the recipients in recipients
.
Remarks
To receive notification when the email has been sent or the operation has been canceled, add an event handler to the SendCompleted event. You can cancel a SendAsync operation by calling the SendAsyncCancel method.
After calling SendAsync, you must wait for the email transmission to complete before attempting to send another email message using Send or SendAsync.
Before calling this method, the Host and Port properties must be set either through the configuration files or by setting the properties or passing this information into the SmtpClient(String, Int32) constructor.
If the SMTP host requires credentials, you must set them before calling this method. To specify credentials, use the UseDefaultCredentials or Credentials property.
If you receive an SmtpException exception, check the StatusCode property to find the reason the operation failed. The SmtpException can also contain an inner exception that indicates the reason the operation failed.
When sending email using SendAsync to multiple recipients, if the SMTP server accepts some recipients as valid and rejects others, a SmtpException is thrown with a NullReferenceException for the inner exception. If this occurs, SendAsync fails to send email to any of the recipients.
Your application can detect a server certificate validation error by examining the Error property passed into the SendCompletedEventHandler delegate.
The Timeout property does not have any effect on a SendAsync call.
To send mail and block while it is transmitted to the SMTP server, use one of the Send methods.
Note
If the EnableSsl property is set to true
, and the SMTP mail server does not advertise STARTTLS in the response to the EHLO command, then a call to the Send or SendAsync methods will throw an SmtpException.