C# 如何识别 SmtpClient.Send() 中的未知用户电子邮件地址

C# How to identify unknown user email address in SmtpClient.Send()

我正在使用以下代码在我公司内部通过我们自己的中继服务器发送电子邮件:

using (MailMessage em = new MailMessage()) {

    em.From = new MailAddress("noreply@mycompany.com", "From Me");
    em.Priority = MailPriority.High;
    em.IsBodyHtml = true;

    try {
        em.To.Add(new MailAddress("Addy_1@mycompany.com"));
        em.To.Add(new MailAddress("Addy_2@mycompany.com"));
        :
        :
        em.To.Add(new MailAddress("Addy_99@mycompany.com"));
    } 
    catch (Exception e) {
        Log.Write(e);
    }

    em.Subject = "My Subject";
    em.Body = "Email body";
}

using (SmtpClient smtp = new SmtpClient()) {

    smtp.UseDefaultCredentials = true;
    smtp.Host = "smtprelay.mycompany.com";

        smtp.Send(em);
    }

}

如果任何电子邮件不再有效,则在您实际尝试 .send() 电子邮件之前不会报告任何内容,到那时为时已晚,您最终会得到:

Mailbox unavailable. The server response was: 5.1.1 User unknown
at System.Net.Mail.SmtpClient.Send(MailMessage message)
   at SendEmail.ProcessRequest(HttpContext context) in C:\inetpub\wwwroot\site\SendEmail.ashx:line 104

有什么方法可以事先执行此电子邮件验证吗? .To.Add() 似乎没有发出任何警报。或者,一旦失败,是否有任何方法可以确定哪个电子邮件地址是错误的?

您应该能够 try/catch Send 方法并捕获 SmtpFailedRecipientsException 或 SmtpFailedRecipientException

SmtpFailedRecipientsException

SmtpFailedRecipientException

对于单个收件人异常有一个 FailedRecipient 属性:

https://docs.microsoft.com/en-us/dotnet/api/system.net.mail.smtpfailedrecipientexception.failedrecipient?view=netcore-3.1