SmtpClient.SendAsync code overview

What is the correct way of disposal SmtpClient

and MailMessage

use SendAsync

?

I copied my code below.

{
...
var client = new SmtpClient {Host = _smtpServer};
client.SendCompleted += SendCompletedCallback;
var userState = mailMessage;
client.SendAsync(mailMessage, userState);
...
}

private static void SendCompletedCallback(object sender, 
    AsyncCompletedEventArgs e)
{
    // Get the unique identifier for this asynchronous operation.
    var mailMessage= (MailMessage)e.UserState;

    if (e.Cancelled)
    {
        Log.Info(String.Format("[{0}] Send canceled.", mailMessage));
    }
    if (e.Error != null)
    {
        Log.Error(String.Format("[{0}] {1}", mailMessage, e.Error));
    }
    else
    {
        Log.Info("Message sent.");
    }
    mailMessage.Dispose();
}

      

Eliminating MailMessage

after client.SendAsync(...)

raises an exception. I need to dispose of it in a callback handler.

+2


a source to share


2 answers


It looks right.



Note that it MailMessage

does not override ToString

, so your logs will just say [MailMessage] Send cancelled

.
You might want to use Subject

proeprty (or some other property).

+1


a source


I think this might help



   client.SendCompleted += (s, e) => { client.Dispose(); message.Dispose(); };

      

+2


a source







All Articles