[英]Catch the mail address if failed
我正在使用smtp將郵件發送到多個地址,我想獲取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)。
解決方案
在client.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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.