1

Is there a way in code to check if an SmtpClient and NetworkCredential is valid as part of a HealthCheck. I don't particularly want to be generating emails every 10 mins, but I'd like to know that the server is responsive and more importantly that the NetworkCredentials haven't been reset without us knowing about it :-)

Current code block is this; but as far as I can tell this isn't making any calls out from the service.

public bool IsHealthy()
{
    try
    {
        var smtp = new SmtpClient(this.options.SmtpHost, this.options.SmtpPort)
        {
            UseDefaultCredentials = false,
            DeliveryMethod = SmtpDeliveryMethod.Network,
            Credentials = new NetworkCredential(
                this.options.EmailUserName, 
                this.options.EmailPassword,
                this.options.EmailDomain)
         };

         // Should really be calling something in here?
         smtp.Dispose();
         return true;
    }
    catch
    {
        return false;
    }
}
Ross Halliday
  • 785
  • 6
  • 19
  • well you can ping the server (or telnet on the SMTP port) to check if it's alive. Although of course, it might be dead a few seconds later, so it's never a 100% guarantee. You'll never know for certain if you'll get a connection until you actually try to make that specific connection. But as a general health check it's probably adequate. Within the C# app itself you could do more to handle failures (like implementing retries, exponential backoff, circuit breaker etc) if reliability is a big issue. – ADyson Dec 04 '19 at 15:58
  • https://stackoverflow.com/questions/372742/can-i-test-smtpclient-before-calling-client-send Seems like you have to do this and try googling - was already asked and answered multiple times. – misticos Dec 04 '19 at 15:59
  • As for the credentials, why would they get reset? Aren't you using a service account with a fixed password? That sounds like more of an organisational process issue than a technical problem. – ADyson Dec 04 '19 at 15:59
  • The credentials :-) yes, they shouldn't change; but in the past they have and we're just making sure we don't get caught out again... – Ross Halliday Dec 04 '19 at 16:02
  • Grand, I suspected it might involve dropping down a layer. I'll review the other question that I missed and post back an answer. – Ross Halliday Dec 04 '19 at 16:04
  • Does this answer your question? [Can I test SmtpClient before calling client.Send()?](https://stackoverflow.com/questions/372742/can-i-test-smtpclient-before-calling-client-send) – Casey Crookston Dec 04 '19 at 16:06
  • Aye, I think it will be; I'm just testing an Api Health check then I'll have a look at it :-) – Ross Halliday Dec 04 '19 at 16:11

1 Answers1

0

Guys in the comments section are correct, it's been asked before [Can I test SmtpClient before calling client.Send()?

Doesn't get me a check on the Network Credentials but at least know that the smtp server is available.

Ross Halliday
  • 785
  • 6
  • 19