如何处理system.net.mail.smtpfailedrecipientexception接收失败
本文关键字:smtpfailedrecipientexception mail 失败 net system 何处理 处理 | 更新日期: 2023-09-27 18:12:18
我想发送电子邮件到多个地址(超过1000个用户),并使用以下代码,当我使用它发送电子邮件到少于100个用户它的工作,但对于超过100个用户它不工作,抛出smtpfailedrecipientexception失败的收件人!为什么?我怎样才能发送电子邮件到有效的地址,并得到这个错误的便车?
public void SendMailMessage (string[] to,string message,string subject)
{
MailMessage mMailMessage = new MailMessage ();
int lenght = to.GetLength(0);
if (lenght > 1) {
foreach (string email in to) {
mMailMessage.Bcc.Add ( email );
}
}
else {
mMailMessage.To.Add ( to[0] );
}
mMailMessage.From = new MailAddress ("no-replay@mycompany.net");
SmtpClient mSmtpClient = new SmtpClient ();
mMailMessage.Body = message;
mMailMessage.IsBodyHtml = true;
mMailMessage.Priority = MailPriority.Normal;
mMailMessage.Subject = subject;
mSmtpClient.EnableSsl = true;
ServicePointManager.ServerCertificateValidationCallback = delegate(object s,X509Certificate certificate,X509Chain chain, SslPolicyErrors sslPolicyErrors) {return true;};
try {
mSmtpClient.Send (mMailMessage);
}
catch (SmtpFailedRecipientsException ex){
for (int i = 0; i < ex.InnerExceptions.Length; i++)
{
SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
if (status == SmtpStatusCode.MailboxBusy ||
status == SmtpStatusCode.MailboxUnavailable)
{
Logger.Debug("Delivery failed - retrying in 5 seconds.");
System.Threading.Thread.Sleep(5000);
//client.Send(message);
mSmtpClient.Send (mMailMessage);
}
else
{
Logger.Debug (string.Format ("Failed to deliver message to {0},{1}", ex.InnerExceptions[i].FailedRecipient, i));
}
}
}
catch (Exception ex)
{
Logger.Debug (string.Format("Exception caught in RetryIfBusy(): {0}", ex.ToString() ));
}
}
看起来您正在使用的SMTP服务器拒绝有超过100个收件人的邮件。
你可以:
- 使用分发列表而不是直接向每个收件人发送消息
- 发送不超过100个收件人的多条消息
- 通知服务器管理员更改限制
但是请注意,当您向数百个外部收件人发送消息时,垃圾邮件过滤器可能会将它们标记为垃圾邮件。
我在一个Microsoft文档中发现异常处理如下:
var client = new System.Net.Mail.SmtpClient();
try
{
client.Send(mailMessage);
}
catch (SmtpFailedRecipientsException ex)
{
for (int i = 0; i < ex.InnerExceptions.Length; i++)
{
SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
if (status == SmtpStatusCode.MailboxBusy ||
status == SmtpStatusCode.MailboxUnavailable)
{
Console.WriteLine("Delivery failed - retrying in 5 seconds.");
System.Threading.Thread.Sleep(5000);
client.Send(mailMessage);
}
else
{
Console.WriteLine("Failed to deliver message to {0}",
ex.InnerExceptions[i].FailedRecipient);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in RetryIfBusy(): {0}",
ex.ToString());
}
但是我不知道如何为这个异常生成异常场景Microsoft link - for mode details