通过System.Net.Mail发送电子邮件时捕获550 5.1.1 RESOLVER.ADR.RecipNotFound错误

时间:2013-01-11 15:39:20

标签: c# system.net.mail

我正在使用Sytem.Net.Mail通过Exchange服务器(在另一台计算机上)通过C#中的Web应用程序发送电子邮件。 (请注意,每个客户都可以设置smtp配置,因此他们可能不会使用Exchange。)

发送电子邮件时,如果邮件发送到无法投递的地址,则会抛出异常。 Exchange 向我发送一封电子邮件,告诉我邮件未发送。

以下是信息:

Diagnostic information for administrators:

Generating server: (exchange server)

(wrong address)
#550 5.1.1 RESOLVER.ADR.RecipNotFound; not found ##

Original message headers:

Received: from (webserver) by (exchangeserver) with Microsoft SMTP Server id (blah); Fri, 11 Jan 2013 10:16:02 -0500
MIME-Version: 1.0
From: (me)
To: (wrong address)
Date: Fri, 11 Jan 2013 10:16:02 -0500
Subject: (blah)
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: base64
Message-ID: (blah)
Return-Path: (me)

这是因为Exchange服务器上的配置设置吗?还有另一种方法可以捕获这个(可能是我异步发送邮件),或者我无法确定邮件是否失败?

请注意,作为要求,我必须向每个收件人发送单独的电子邮件。所以有一个for循环向每个地址发送一封电子邮件。对于无效的地址,没有捕获异常,因此系统认为电子邮件已成功发送。

SendEmailError是一个只保存错误信息的类。最终返回的是没有项目的List。当向无效地址发送消息时,代码不会进入两个catch块中的任何一个。

代码:

public List<SendEmailError> SendEmail(MailAddress fromAddress, string subject, string body, bool isBodyHTML, MailPriority priority,
                            IEnumerable<MailAddress> toAddresses)
{
    List<SendEmailError> detectedErrors;

    // create the email message
    MailMessage message = new MailMessage()
    {
        Subject = subject,
        SubjectEncoding = Encoding.UTF8,
        Body = body,
        BodyEncoding = Encoding.UTF8,
        IsBodyHtml = isBodyHTML,
        Priority = priority,
        From = fromAddress
    };

    SmtpClient smtpClient = new SmtpClient("myexchangeserver", 25)
    {
        Credentials  = new NetworkCredential("myid", "mypword", "mydomain");
    };

    foreach (MailAddress toAddress in toAddresses)
    {
        message.To.Clear();
        message.To.Add(toAddress);
        try
        {
            smtpClient.Send(message);
        }
        catch (SmtpFailedRecipientsException ex)
        {
            // if the error was related to the send failing for a specific recipient, log
            // that error and continue.
            SendEmailError error = new SendEmailError();
            error.Type = SendEmailError.ErrorType.SendingError;
            error.Exception = ex;
            detectedErrors.Add(error);
        }
        catch (Exception ex)
        {
            // if the error wasn't related to a specific recipient. add
            // an error and stop processing.
            SendEmailError error = new SendEmailError();
            error.Type = SendEmailError.ErrorType.ConnectionError;
            error.Exception = ex;
            detectedErrors.Add(error);
            break;
        }
    }

    return detectedErrors;
}

0 个答案:

没有答案