11

Is there a way with JavaMail API to check that the mail server used is alive ? If not, how do to it with Java code ?

Thanks by advance for your help.

Denis R.
  • 818
  • 1
  • 9
  • 15

3 Answers3

11

If you've got a reference to a Session instance, you could do the following:

Session s = //a JavaMail session I got from somewhere
boolean isConnected = s.getTransport("smtp").isConnected();

If the mail client is connected to the appropriate SMTP server, it usually means it's alive.

Sean Reilly
  • 21,526
  • 4
  • 48
  • 62
  • 2
    in case you just created a new session and want to call `isConnected()`, initially, you have to call the method `getTransport("smtp").connect()`. – Radu Linu Apr 08 '19 at 15:03
5

From the JavaMail API, you could try sending an email and seeing if it was sent successfully.

From a connectivity standpoint, you could just ping it:

  InetAddress host = InetAddress.getByName("mailserver");
  System.out.println("host.isReachable(1000) = " + host.isReachable(1000));
Icarus
  • 63,293
  • 14
  • 100
  • 115
  • Ok, so you confirm that the first solution is the only one : a server does not need to responde to ping to work correctly. – Denis R. Feb 15 '12 at 15:38
  • @DenisR. Correct, a server may very well ignore ICMP echo requests. – Icarus Feb 15 '12 at 15:40
  • It's not really the only possible solution. SMTP servers may very well ignore ICMP echo requests, but they don't ignore TCP connections to port 25. – Sean Reilly Feb 16 '12 at 10:54
1

From this Link; you can use the following logic:

public boolean isAlive() throws MessagingException {
  session.setDebug(true);
  Transport transport = session.getTransport("smtp");
  transport.connect();
  if (transport.isConnected()) {
    transport.close();
    return true;
  }
  return false;
}
YourAboutMeIsBlank
  • 1,787
  • 3
  • 18
  • 27