gosmtpmonitoringhealth-monitoring

Check if SMTP server is online


How to check if SMTP is online and running?

func (p *sys_ping) smtp(host string) string {
    client, err := smtp.Dial(host)
    if err != nil {
        time.Sleep(time.Duration(p.delay) * time.Second)
        return ""
    }
// check if response code is 220 or something similar to check if server is running
    client.Quit()
    return host
}

The above code is connecting to the SMTP. It works. But how can you check if the response code is 220? I guess the correct code should be 220 to check if the server is running correctly?


Solution

  • As @kostix rightfully remarks smtp.Dial calls smtp.NewClient, which calls _, _, err := text.ReadResponse(220) (GitHub):

    // Dial returns a new [Client] connected to an SMTP server at addr.
    // The addr must include a port, as in "mail.example.com:smtp".
    func Dial(addr string) (*Client, error) {
        // ...
        return NewClient(conn, host)
    }
    
    // NewClient returns a new [Client] using an existing connection and host as a
    // server name to be used when authenticating.
    func NewClient(conn net.Conn, host string) (*Client, error) {
        text := textproto.NewConn(conn)
        _, _, err := text.ReadResponse(220)
        if err != nil {
            text.Close()
            return nil, err
        }
        // ...
    }
    

    So, after smtp.Dial you either have a working SMTP connection (with a 220 response) or get an error back.