Search code examples
c#smtpclientmailmessage

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


I am using the following code to send emails internally at my company on our own relay server:

using (MailMessage em = new MailMessage()) {

    em.From = new MailAddress("[email protected]", "From Me");
    em.Priority = MailPriority.High;
    em.IsBodyHtml = true;

    try {
        em.To.Add(new MailAddress("[email protected]"));
        em.To.Add(new MailAddress("[email protected]"));
        :
        :
        em.To.Add(new MailAddress("[email protected]"));
    } 
    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);
    }

}

If any of the emails are no longer valid, nothing is reported until you actually attempt to .send() the email, by which time it is too late, and you end up with:

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

Is there any way to perform this email validation before hand? .To.Add() doesn't seem to raise any alert. Or, once it fails, is there any way to determine WHICH email address was the one that was bad?


Solution

  • You should be able to try/catch the Send method and catch either SmtpFailedRecipientsException or SmtpFailedRecipientException

    SmtpFailedRecipientsException

    SmtpFailedRecipientException

    There's a FailedRecipient property for the singular recipient exception:

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