1

这是我的代码

foreach (String Email in usersList)
{ 
   if(Regex.IsMatch(Email, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*") 
   {

     SmtpClient smtpClient = new SmtpClient();
     MailMessage message = new MailMessage();
     MailAddress AddressFrom = new MailAddress(emailFrom);
     message.From = AddressFrom;
     MailAddress AddressTo = new MailAddress(Email);
     message.To.Add(Email);
     smtpClient.Send(message);
     message.Dispose();
     smtpClient.Dispose();
   }
}

我需要向列表中的所有用户发送电子邮件。但如果发生异常,循环中断,其余电子邮件将不会发送。还有其他方法可以做到这一点,所以如果无法发送电子邮件,循环会不断迭代并忽略那些失败的?

谢谢!

4

3 回答 3

7

是的,但是您的代码可能需要做大量的工作。

using (SmtpClient smtpClient = new SmtpClient())
{

    foreach (String Email in usersList)
    { 
       if(Regex.IsMatch(Email, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*") 
       {
         using (MailMessage message = new MailMessage())
         {
             try
             {
                 MailAddress AddressFrom = new MailAddress(emailFrom);
                 message.From = AddressFrom;
                 MailAddress AddressTo = new MailAddress(Email);
                 message.To.Add(Email);
                 smtpClient.Send(message);
              }
              catch (Exception e)
              {
                  // log exception and keep going
              }
         }
       }
    }
}

首先,停止打电话Dispose()!当你得到那个异常时,你知道会发生什么吗?Dispose()永远不会被调用。将您的 smtp 分配带到循环之外,这样它就不会在每次迭代时重新分配。然后只需添加一个 try-catch 并抑制异常,记录它们,将它们写入控制台,等等。

于 2013-09-23T17:48:42.230 回答
4

如何使用“try catch”,也就是异常处理语句?

http://msdn.microsoft.com/en-us/library/0yd65esw(v=vs.110).aspx

您的代码将如下所示:

//you don't need a SmtpClient for each recipient
SmtpClient smtpClient = new SmtpClient();

foreach (String Email in usersList)
{ 
   if(Regex.IsMatch(Email, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*") 
   {
     using (MailMessage message = new MailMessage()){
         try
         {
            MailAddress AddressFrom = new MailAddress(emailFrom);
            message.From = AddressFrom;
            MailAddress AddressTo = new MailAddress(Email);
            message.To.Add(Email);
            smtpClient.Send(message);
         } 
         catch (Exception ex)
         {
            Console.WriteLine(ex.Message);
         }
     }
   }
}
于 2013-09-23T17:46:28.247 回答
1

并行编程怎么样?

Parallel.ForEach(usersList, (string email) =>
{ 
   if(Regex.IsMatch(Email, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*") 
   {
     SmtpClient smtpClient = new SmtpClient();
     MailMessage message = new MailMessage();
     MailAddress AddressFrom = new MailAddress(emailFrom);
     message.From = AddressFrom;
     MailAddress AddressTo = new MailAddress(Email);
     message.To.Add(Email);
     smtpClient.Send(message);
     message.Dispose();
     smtpClient.Dispose();
   }
});

异常将在不同的线程中引发,并且一个引发的异常不会导致中断其他任务。当然,您不应该忘记使用using语句,它可以确保正确处理内存。在您的解决方案中,当抛出异常时,即使它被捕获message.Dispose()并且smtp.Dispose()没有被执行。

于 2013-09-23T17:56:28.737 回答