加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 有没有办法使用System.Net.Mail.SendAsync()捕获异常

发布时间:2020-12-16 06:23:21 所属栏目:asp.Net 来源:网络整理
导读:我已经有几种方法可以同步发送电子邮件. 如果电子邮件失败,我使用这个相当标准的代码: static void CheckExceptionAndResend(SmtpFailedRecipientsException ex,SmtpClient client,MailMessage message) { for (int i = 0; i ex.InnerExceptions.Length -1;
我已经有几种方法可以同步发送电子邮件.

如果电子邮件失败,我使用这个相当标准的代码:

static void CheckExceptionAndResend(SmtpFailedRecipientsException ex,SmtpClient client,MailMessage message)
    {
        for (int i = 0; i < ex.InnerExceptions.Length -1; i++)
        {
            var status = ex.InnerExceptions[i].StatusCode;

            if (status == SmtpStatusCode.MailboxBusy ||
                status == SmtpStatusCode.MailboxUnavailable ||
                status == SmtpStatusCode.TransactionFailed)
            {
                System.Threading.Thread.Sleep(3000);
                client.Send(message);
            }
        }
    }

但是,我正在尝试使用SendAsync()实现相同的目标.这是我到目前为止的代码:

public static void SendAsync(this MailMessage message)
    {
        message.ThrowNull("message");

        var client = new SmtpClient();

        // Set the methods that is called once the event ends
        client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);

        // Unique identifier for this send operation
        string userState = Guid.NewGuid().ToString();

        client.SendAsync(message,userState);

        // Clean up
        message.Dispose();
    }

    static void SendCompletedCallback(object sender,AsyncCompletedEventArgs e)
    {
        // Get the unique identifier for this operation.
        String token = (string)e.UserState;

        if (e.Error.IsNotNull())
        {
            // Do somtheing
        }
    }

问题是使用令牌和/或e.Error如何获取异常,以便我可以对StatusCode进行必要的检查然后重新发送?

我整个下午一直在谷歌搜索,但没有找到任何积极的东西.

任何建议表示赞赏

解决方法

e.Error已经在发送电子邮件异步时发生了异常.您可以检查Exception.Message,Exception.InnerException,Exception.StackTrace等,以获取更多详细信息.

更新:

检查Exception是否为SmtpException类型,如果是,则可以查询StatusCode.就像是

if(e.Exception is SmtpException)
{
   SmtpStatusCode  code = ((SmtpException)(e.Exception)).StatusCode;
   //and go from here...
}

和check here了解更多细节.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读