I am working on a project which (unfortunately) requires the maximum framework allowable to be .NET 4.
In this project I am attempting to send an email asynchronously using SendAsync()
but for some reason, it fails to send (or rather, it just doesn't send). Simply put, nothing happens. No error or anything, whats strange is that when I set a breakpoint at the event handler code, and step through the program, it doesn't go into the event handler at any point.
If I use the synchronous method Send();
it works flawlessly.
The only difference in my code is the using an event handler for the SendAsync();
method. (SendCompleteEventHandler
)
below is the code I have tried so far to send an email.
private static void SendMailAsync()
{
const string FROM = "[email protected]";
const string TO = "[email protected]";
string SUBJECT = "THIS IS A TEST";
string BODY = "THIS IS A TEST";
const string SMTP_USERNAME = "UserName"; //SMTP username.
const string SMTP_PASSWORD = "Password"; // SMTP password.
const string HOST = "host.testsmtp.com";
const int PORT = 2587;
// Create an SMTP client
SmtpClient client = new SmtpClient(HOST, PORT);
client.SendCompleted += new SendCompletedEventHandler(Client_SendComplete);
// Create a network credential
client.Credentials = new System.Net.NetworkCredential(SMTP_USERNAME, SMTP_PASSWORD);
client.EnableSsl = true;
string userToken = "testmsg1";
// Send the email.
client.SendAsync(FROM, TO, SUBJECT, BODY, userToken);
client.Dispose();
}
private static void Client_SendComplete(object sender, AsyncCompletedEventArgs e)
{
string token = (string) e.UserState;
if (e.Error != null)
{
MessageBox.Show(e.Error.ToString());
}
else
{
MessageBox.Show("Message sent.");
}
}
private void button2_Click(object sender, EventArgs e)
{
SendMailAsync();
}
Is there something I am just flat out missing? Thanks.
The operation called asynchronous
if it's being run asynchronously
, in background. So, you should consider the SendAsync
method as start for the operation. After this, you're disposing the client which actually run the operation, without waiting for it to complete, so you're, like, saying: hey, start this for me, please... Oh, nevermind.
So, you probably should remove the Dispose
method from the code right after the sending. You can dispose your client in Client_SendComplete
(sender
object probably is a client), or you can make a static field in your class, and dispose it after your program is shut down (as far as I can see, it's a WinForms project so you can handle some windows events)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With