发送邮件时如何捕获特定的异常?

时间:2011-05-19 06:38:45

标签: c# .net exception-handling

我有以下代码

try
{
  if (!bDebug)
    smtp.Send(m);
}
catch (Exception e)
{
  wl("Meldingen kunne ikke sendes til en eller flere mottakere.", ConsoleColor.Red);
  wl(e.Message, ConsoleColor.DarkRed);
  using (var errorfile = System.IO.File.CreateText("error-" + DateTime.Now.Ticks + ".txt"))
  {
    errorfile.WriteLine(e.StackTrace);
    if (e.GetType() == typeof(SmtpFailedRecipientException))
    {
      var se = (SmtpFailedRecipientException) e;
      errorfile.WriteLine(se.FailedRecipient);
    }
    errorfile.WriteLine(e.ToString());
  }
}

其中wl是使用颜色写入控制台的快捷方式,第一行中的文字显示“消息无法发送给一个或多个收件人。

之前我只抓住了SmtpFailedRecipientException,但是当它开始在其他一些步骤中失败时,我将通用Exception推到了那里。所以我想知道的部分是我将Exception对象转换为更具体的对象来获取FailedRecipient属性。可以/应该以另一种更恰当的方式完成吗?看起来有点笨拙......

2 个答案:

答案 0 :(得分:8)

您可以拥有多个catch分支:

catch (SmtpFailedRecipientException se)
{
  using (var errorfile = System.IO.File.CreateText("error-" + DateTime.Now.Ticks + ".txt"))
  {
    errorfile.WriteLine(se.StackTrace);  
    // variable se is already the right type, so no need to cast it      
    errorfile.WriteLine(se.FailedRecipient);       
    errorfile.WriteLine(se.ToString());
  }
}
catch (Exception e)
{
  wl("Meldingen kunne ikke sendes til en eller flere mottakere.", ConsoleColor.Red);
  wl(e.Message, ConsoleColor.DarkRed);   

  // for other error types just write the info without the FailedRecipient
  using (var errorfile = System.IO.File.CreateText("error-" + DateTime.Now.Ticks + ".txt"))
  {
    errorfile.WriteLine(e.StackTrace);        
    errorfile.WriteLine(e.ToString());
  }

}

答案 1 :(得分:4)

您可以尝试这样的事情(source):

  

我们将学习如何捕捉/处理不同类型的   使用时发送电子邮件时可能发生的异常/错误   ASP.Net。我们将使用不同的方法实现错误/异常处理   System.Net.Mail中提供的异常类。

     

首先了解如何使用ASP.Net发送电子邮件访问this link。请注意,在上面的文章中(通过链接引导)   'SendEmails'只捕获一个通用异常,以防ASP.Net   发送电子邮件时遇到错误就像是“发送”   电子邮件失败等'。我们将扩展错误处理功能   上面的文章。因此,让我们开始解决我们的解决方案   以前创建的。我们已经放了一个抓住的try-catch块   一个通用的例外,几乎没有说明可能会发生什么   错误。让我们马上捕捉不同类型的例外:

     

抓住SmtpExceptionSmtpException类有一个属性   'StatusCode'实际上是一个获取的枚举   电子邮件时SMTP服务器返回的错误/异常代码值   消息被传输。它还提供了更多细节   电子邮件发送过程中可能发生的错误/异常。例如

catch (SmtpException smtpException) 
{ // You can put a switch block to check for different exceptions or errors    

 // To checks if the destination mailbox is busy 
 if (smtpException.StatusCode == SmtpStatusCode.MailboxBusy) 
   throw smtpException; 

 // To check if the client is authenticated or is allowed to send email using the specified SMTP host 
 if (smtpException.StatusCode == SmtpStatusCode.ClientNotPermitted) 
   throw smtpException; 
 // The following code checks if the email message is too large to be stored in destination mailbox 

 if (smtpException.StatusCode == SmtpStatusCode.ExceededStorageAllocation) 
   throw smtpException; 
 // To check if the email was successfully sent to the SMTP service 

 if (smtpException.StatusCode == SmtpStatusCode.Ok) 
   throw smtpException; 
 // When the SMTP host is not found check for the following value 

 if (smtpException.StatusCode == SmtpStatusCode.GeneralFailure) 
   throw smtpException;             
} 
     

抓住SmtpFailedRecipientException:The   SmtpFailedRecipientException类处理与之相关的异常   电子邮件的收件人,例如SMTP无法发送电子邮件   收件人。 SmtpFailedRecipientException发生在SmtpClient   无法完成SmtpClient.Send()SmtpClient.SendAsync()   对特定收件人的操作。要捕获此异常,请使用   以下代码:

catch (System.Net.Mail.SmtpFailedRecipientException smtpFailedRecipientException) 
{ 
 // Get the email that is causing email sending failed exception 
 String emailCausingException = smtpFailedRecipientException.FailedRecipient; 

 // Get the status code why and what is actually causing an email sending error 
 System.Net.Mail.SmtpStatusCode statusCode = smtpFailedRecipientException.StatusCode; 

 // Take some action either re-send the email again or do some error handling code here 
}
     

抓住SmtpFailedRecipientsException:The   SmtpFailedRecipientsException实际上是一个集合   SmtpFailedRecipientException个用于同一目的的对象。它是   用于在SmtpClient无法发送电子邮件时处理异常   一个或多个收件人。

catch (System.Net.Mail.SmtpFailedRecipientsException smtpFailedRecipientsException) 
{ 
 ArrayList emailCausingException = new ArrayList(); 

 foreach (SmtpFailedRecipientException smtpFailedRecipientException 
               in smtpFailedRecipientsException.InnerExceptions) 
{ 
   // Get the email that is causing email sending failed exception 
   // Add it to a list of emails with exceptions 
   emailCausingException.Add(smtpFailedRecipientException.FailedRecipient);

   // Get the status code why and what is actually causing an email sending error 
   System.Net.Mail.SmtpStatusCode statusCode = smtpFailedRecipientException.StatusCode; 
   // Take some action either re-send the email again or do some error handling 
   // You can also log or print this status code for an individual recipient here 
   if (statusCode == SmtpStatusCode.MailboxBusy) 
   { 
     //Re-Send email after some time 
     System.Threading.Thread.Sleep(1000); 
     //smtpClient.Send(); 
     //Email sending code here 
   } 
 } 
}
相关问题