Search code examples
asp.net-mvc-3mvcmailer

Logging errors when sending ASync email with MvcMailer


I'm using the excellent MvcMailer package to send email from within my application. I'm using the SendAsync() method to send email, and would like to log errors + dispose of attachments i.e.

MailMessage message = UserMailer.SendSomeEmail(emailViewModel);

        var client = new SmtpClientWrapper();
        client.SendCompleted += (sender, e) =>
        {
            if (e.Error != null || e.Cancelled)
            {
                Logger.LogError(e.Error);
            }
            if (message != null)
            {
                message.Attachments.Dispose();
                message.Dispose();
            }
            client.Dispose();
        };
        message.SendAsync("this means nothing afaik", client);

This works great, but it would get too painful to repeat the same snippet all over wherver I need to send email.

How should I set this up so that I can log any errors + dispose of message attachments when the async call is completed? There has to be a better way!


Solution

  • If what you're trying to do is to avoid having to write that logging and cleanup code every time you send an async email, the answer is simple -- stop using anonymous methods. Just take your current code and put it in a regular method like this:

    public void AsyncSendCompleted(object sender, EventArgs e) 
    {
      // Use an appropriate type instead of EventArgs so you can get
      // stuff like e.Cancelled and e.Error
    
      // The rest of your code goes here
    }
    

    Now use this method as the event handler for your SendCompleted event:

    client.SendCompleted += AsyncSendCompleted;