I am using SmtpClient to send an email to multiple recipients. As employees leave the company, their email addresses become invalid. Since their email addresses remain in our database until deleted manually, trying to send an email to them causes our application to throw an exception during SmtpClient.Send(MailMessage)
. However, in spite of the exception being thrown, it still sends the email. This is a problem because we want to handle this error by blocking the user's attempt to save the record and display a friendly message advising to delete any invalid associates from the database.
If there were a way to iterate through all the recipeients to make sure they're all valid, we can keep all emails from being sent until the user satisifes a set of conditions.
Its a very old question, I don't know if you have got it solved.
As per MSDN: http://msdn.microsoft.com/en-us/library/swas0fwc(v=vs.100).aspx
When sending e-mail using Send to multiple recipients and the SMTP server accepts some recipients as valid and rejects others, Send sends e-mail to the accepted recipients and then a SmtpFailedRecipientsException is thrown. The exception will contain a listing of the recipients that were rejected.
This is an example of catching this exception taken from MSDN:
try {
client.Send(message);
}
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) {
Console.WriteLine("Delivery failed - retrying in 5 seconds.");
System.Threading.Thread.Sleep(5000);
client.Send(message);
}
else {
Console.WriteLine("Failed to deliver message to {0}", ex.InnerExceptions[i].FailedRecipient);
}
}
}
Complete example here: http://msdn.microsoft.com/en-us/library/system.net.mail.smtpfailedrecipientsexception.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
Internally the Send
uses the statuscode
returned from RCPT TO
command to raise the appropriate exception.
Check the implementation for PrepareCommand
in the RecipientCommand.Send
method of smtpTransport.SendMail
(This method is called internally by SmtpClient.Send
). It uses RCPT TO
to get the StatusCode
which is then parsed in the CheckResponse
method and accordingly the SmtpFailedRecipientsException
is raised. However, VRFY and RCPT both are not very reliable because the mail servers tend to delay (throttle NDR) or swallow the response as an anti-spam measure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With