1

我正在使用 Sytem.Net.Mail 通过 C# 中的 Web 应用程序通过 Exchange 服务器(在另一台机器上)发送电子邮件。(请注意,每个客户都可以设置 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)

这是因为交换服务器上的配置设置吗?是否有另一种方法来捕捉这个(也许如果我异步发送邮件),或者我无法找出消息是否失败?

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

SendEmailError 是一个只保存错误信息的类。最终返回的是一个没有项目的列表。当向无效地址发送消息时,代码不会进入两个 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;
}
4

0 回答 0