C# 4.0 如果失败,请捕获邮件地址

C# 4.0 如果失败,请捕获邮件地址,c#-4.0,C# 4.0,我正在使用smtp将邮件发送到多个地址,我想获取get sendig失败的邮件地址 message.To.Add(new System.Net.Mail.MailAddress("xxx@gmail.com")); message.To.Add(new System.Net.Mail.MailAddress("yyy@gmail.co.in")); message.To.Add(new System.Net.Mail.MailAddress("zzz@gmail.com")); client.

我正在使用smtp将邮件发送到多个地址,我想获取get sendig失败的邮件地址

message.To.Add(new System.Net.Mail.MailAddress("xxx@gmail.com"));
message.To.Add(new System.Net.Mail.MailAddress("yyy@gmail.co.in"));
message.To.Add(new System.Net.Mail.MailAddress("zzz@gmail.com")); 
client.Send(message);
在上面的列表中,第一封和第三封邮件已发送,第二封邮件无法发送。 所以我想捕获失败的邮件地址(yyy@gmail.co.in)


解决方案请在您的
客户机中.Send()
方法您应该调用
try catch
块中的每个特定发送方法,然后处理故障。 另一个选项是重新显示此类异常,并在附加代码的
catch
块中捕获它:

try {
client.Send(message);
}
catch (Exception e)
{
//do smth with it
}

告诉我们有关您的
Send()
方法和
client
对象的更多信息。这会让我们更加具体。

如果您使用的是c#SmtpClient,并且可以使用SendAsync方法,那么这非常容易

//client and MailMessage construction
client.SendCompleted += (sender, eventArgs) => {
     string emailAddress = eventArgs.UserState as String;
     if (eventArgs.Error != null) { 
        //an error occured, you can log the email/error         
     }
     else //the email sent successfully you can log the email/success
};
client.SendAsync(mail, mail.Sender.Address);
如果您愿意,可以使用新的SendCompletedEventHandler(methodName)替换lambda; 并且有一个类似的方法

... methodName(object sender, System.ComponentModel.AsyncCompletedEventArgs eventArgs)
{
  string emailAddress = eventArgs.UserState as String;
         if (eventArgs.Error != null) { 
            //an error occured, you can log the email/error
         }
         else //the email sent successfully you can log the email/success
}