Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SmtpClient.SendAsync not sending email versus SmtpClient.Send

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.

like image 800
tastydew Avatar asked Jan 05 '17 21:01

tastydew


1 Answers

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)

like image 77
VMAtm Avatar answered Oct 07 '22 20:10

VMAtm