1

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!

seekay
  • 2,493
  • 3
  • 27
  • 33

1 Answers1

0

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;
Ragesh
  • 2,800
  • 2
  • 25
  • 36
  • Thanks! I was trying to also dispose of the MailMessage object + add the eventhandler in a DRY fashion, but I guess that's not possible without modifying the MvcMailer source itself. – seekay Nov 18 '11 at 23:02
  • You should use a `using` block to take care of the dispose. If you really need to make adding the event handler repeatable, you could look at using the factory pattern. Just wire up whatever you need inside the factory. – Ragesh Nov 19 '11 at 04:38