【问题标题】:Logging errors when sending ASync email with MvcMailer使用 MvcMailer 发送异步电子邮件时记录错误
【发布时间】:2011-11-18 11:25:24
【问题描述】:

我正在使用出色的 MvcMailer 包从我的应用程序中发送电子邮件。 我正在使用 SendAsync() 方法发送电子邮件,并希望记录错误 + 处理附件,即

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);

这很好用,但是在我需要发送电子邮件的地方重复相同的 sn-p 会太痛苦。

我应该如何进行设置,以便在异步调用完成时记录任何错误并处理消息附件?一定有更好的办法!

【问题讨论】:

    标签: asp.net-mvc-3 mvcmailer


    【解决方案1】:

    如果您想要避免在每次发送异步电子邮件时都编写日志记录和清理代码,那么答案很简单——停止使用匿名方法。只需将您当前的代码放入常规方法中,如下所示:

    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
    }
    

    现在将此方法用作您的 SendCompleted 事件的事件处理程序:

    client.SendCompleted += AsyncSendCompleted;
    

    【讨论】:

    • 谢谢!我也试图处理 MailMessage 对象 + 以 DRY 方式添加事件处理程序,但我想如果不修改 MvcMailer 源本身是不可能的。
    • 您应该使用 using 块来处理处置。如果您确实需要使添加事件处理程序可重复,您可以考虑使用工厂模式。只需在工厂内连接您需要的任何东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-08
    • 2015-02-05
    相关资源
    最近更新 更多