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

I have a simple smtpClient:

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

I may have another host: smtp.gmail.com , smtp.yandex.ru , etc.

When executing smtp.Send(message); I have another exception (it depends on the host) due to the same problem - 2-factor verification is turned 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’m not talking about exceptions from other mail providers now, but how to throw an exception ("you need to enable two-factor verification") only once? Is it possible? Or how to minimize code duplication?

+5
source share
1 answer

I'm not sure how you choose which host to use (an if or switch ?), But you might consider adding two new client classes that inherit from SmtpClient, for example. for 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 } } } 

In addition, you can implement the embedded interface and use IoC (or a strategy template, etc.) to enter the correct client based on your configuration, for example.

 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 may be too much, but it can avoid SRP violation and the need to execute conditional logic in the method you are currently using to send email.

0
source

Source: https://habr.com/ru/post/1241135/


All Articles