4

我已经有几种方法可以同步发送电子邮件。

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

    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 进行必要的检查然后重新发送?

我整个下午都在谷歌上搜索,但没有发现任何积极的东西。

任何建议表示赞赏。

4

1 回答 1

4

e.Error已经有发送异步电子邮件时发生的异常。您可以查看Exception.MessageException.InnerExceptionException.StackTrace等以获取更多详细信息。

更新:

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

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

在此处查看更多详细信息。

于 2013-02-28T15:15:09.857 回答