1

编辑 我使用以下代码在 C# 中发送批量电子邮件。但是,当其中一个收件人的电子邮件地址无效时,即使电子邮件地址有效的其他收件人也不会发送电子邮件,我遇到了一个例外:

system.net.mail.smtpfailedrecipientsexception 收件人失败

即使其中一个电子邮件地址无效,有什么方法可以将电子邮件发送给其他有效的收件人?

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() ));
    }

}

此外,在我将字符串电子邮件地址发送到 SendMailMessage 方法之前,我通过这种方法检查它们是否有效:

public bool IsValidEmail(string emailaddress)
    {
        try
        {
            MailAddress m = new MailAddress(emailaddress);
            return true;
        }
        catch (FormatException)
        {
            return false;
        }
    }
4

2 回答 2

1

就我个人而言,我会循环并多次调用 Send(每个地址一个)。如果将密件抄送发送到多个地址,可能会出现很多问题,包括邮件服务器由于地址过多而拒绝它。

于 2013-05-05T07:11:30.833 回答
0

当使用 Send 向多个收件人发送电子邮件并且 SMTP 服务器接受某些收件人为有效收件人并拒绝其他收件人时,Send 会向接受的收件人发送电子邮件,然后引发 SmtpFailedRecipientsException。例外将包含被拒绝的收件人列表。

来自文档:http: //msdn.microsoft.com/en-us/library/swas0fwc.aspx

听起来它完全符合您的要求,请尝试将其发送到您可以访问的电子邮件,然后查看您是否收到了电子邮件。

于 2013-05-05T07:09:04.183 回答