简体   繁体   中英

How to correctly handle System.Net.Mail.SmtpException?

I have a simple smtpClient:

var smtp = new SmtpClient { Host = host, ...};
smtp.Send(message);

I can have a different host: smtp.gmail.com , smtp.yandex.ru etc.

When smtp.Send(message); executed I have different exception (depends on the host) due to the same problem - 2-factor verification is off.

For gmail its System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.

For yahoo and yandex its System.Net.Mail.SmtpException depth 0: The operation has timed out. (0x80131500) System.Net.Mail.SmtpException depth 0: The operation has timed out. (0x80131500)

I don't now about others mail providers exception but how to correctly throw exception ("you need to enable 2-factor verification") just once? Is it possible? Or how to minimize code duplication?

I'm not sure how you are choosing which host to use (an if or switch statement?) but you could consider adding two new client classes which inherit from SmtpClient, eg for a YahooClient:

class YahooClient : SmtpClient {

     private const string Host = "smtp.yahoo.com";

     Send(MailMessage message) { 

          /// Call base send and handle exception            
          try {
             base.Send(message)
          }
          catch(ex as SmtpException) {
              // Handle accordingly
          }
     }
}

Furthermore, you could introduce implement a suitable interface and use IoC (or strategy pattern etc.) to inject the correct client based on your configuration, eg

class YahooClient : SmtpClient, IMySmtpClient {

}

interface IMySmtpClient {
    void Send(MailMessage message);
}

class ConsumingMailSender(IMySmtpClient client) {

       // Create message and send
       var message = new MailMessage etc....

       client.Send(message);
}

This is perhaps overkill but could avoid violating SRP and having to perform conditional logic in the method you are currently using to send the email in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM