开发者

Error handling the SmtpClient object

I'm using the code below to process the results of mail sending using System.Net.Mail.SmtpClient and am having problems trapping a true 'send failure' vs 'opps...let me try that again, oh great, it worked' conditions.

My SendMail method closes with this:

    smtp.SendCompleted += SendCompletedCallback;
    smtp.SendAsync(Msg, userState);

and the callback:

    private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
    {
        var msg= (MailMessage)e.UserState;
        if (e.Cancelled)
        {
            Logger("Cancelled - " + msg.Subject.ToString()+ " : " + msg.To.ToString());
        }
        if (e.Error != null)
        {
            Logger("ERROR: " + msg.To.ToString() + " : " + e.Error.ToString());
        }
        else
        {
            Logger("EmailGateway: " + msg.Subject.ToString());
        }

    }

The problem I'm finding is multiple passes of the same message thru the if (e.Error != null) branch - sometimes the subsequent attempt completes successfully, sometimes not.

In other words, in my Log, sometimes I'm seeing 2 lines on the same message (a true error condition because the message was not delivered) but I'm also seeing instances where the开发者_运维百科 Log shows just a single error but then further it logs a success. So sometimes, even though the Log shows a error for a given message - the mail was in fact, sent.

It's probably worth pointing out that my Log is not showing any messages as 'Canceled'. It's not like 'we'll give it 2 tries then we hit 'cancelled'. In instances showing 2 attempts with nothing sent (a true fail condition) it looks as though the remote smtp server triggered the error condition twice on the same message.

So if I want to add more robust error handling beyond just logging stuff, how can I tell true error conditions vs. a retry that results in success?

Here's the full exception being returned. I should parse for 'Try again later' before logging the error condition, shouldn't I?

System.Net.Mail.SmtpException: Service not available, closing transmission channel. The server response was: 4.7.0 Temporary System Problem. Try again later (WS). e22sm1141297yba.20 at System.Net.Mail.SendMailAsyncResult.End(IAsyncResult result) at System.Net.Mail.SmtpTransport.EndSendMail(IAsyncResult result) at System.Net.Mail.SmtpClient.SendMailCallback(IAsyncResult result)

thx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜