这是我的代码
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();
}
}
我需要向列表中的所有用户发送电子邮件。但是,如果发生异常,则循环中断,其余电子邮件将不会发送。 还有其他方法我可以这样做,所以如果无法发送电子邮件,循环会继续迭代,只是忽略失败的那些?
谢谢!
答案 0 :(得分: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并禁止异常,记录它们,将它们写入控制台,无论如何。
答案 1 :(得分:4)
如何使用“try catch”,a.k.a。异常处理语句?
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);
}
}
}
}
答案 2 :(得分: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()
也未执行。