smtp_check.phps 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. /**
  3. * This uses the SMTP class alone to check that a connection can be made to an SMTP server,
  4. * authenticate, then disconnect
  5. */
  6. //SMTP needs accurate times, and the PHP time zone MUST be set
  7. //This should be done in your php.ini, but this is how to do it if you don't have access to that
  8. date_default_timezone_set('Etc/UTC');
  9. require '../PHPMailerAutoload.php';
  10. //Create a new SMTP instance
  11. $smtp = new SMTP;
  12. //Enable connection-level debug output
  13. $smtp->do_debug = SMTP::DEBUG_CONNECTION;
  14. try {
  15. //Connect to an SMTP server
  16. if (!$smtp->connect('mail.example.com', 25)) {
  17. throw new Exception('Connect failed');
  18. }
  19. //Say hello
  20. if (!$smtp->hello(gethostname())) {
  21. throw new Exception('EHLO failed: ' . $smtp->getError()['error']);
  22. }
  23. //Get the list of ESMTP services the server offers
  24. $e = $smtp->getServerExtList();
  25. //If server can do TLS encryption, use it
  26. if (array_key_exists('STARTTLS', $e)) {
  27. $tlsok = $smtp->startTLS();
  28. if (!$tlsok) {
  29. throw new Exception('Failed to start encryption: ' . $smtp->getError()['error']);
  30. }
  31. //Repeat EHLO after STARTTLS
  32. if (!$smtp->hello(gethostname())) {
  33. throw new Exception('EHLO (2) failed: ' . $smtp->getError()['error']);
  34. }
  35. //Get new capabilities list, which will usually now include AUTH if it didn't before
  36. $e = $smtp->getServerExtList();
  37. }
  38. //If server supports authentication, do it (even if no encryption)
  39. if (array_key_exists('AUTH', $e)) {
  40. if ($smtp->authenticate('username', 'password')) {
  41. echo "Connected ok!";
  42. } else {
  43. throw new Exception('Authentication failed: ' . $smtp->getError()['error']);
  44. }
  45. }
  46. } catch (Exception $e) {
  47. echo 'SMTP error: ' . $e->getMessage(), "\n";
  48. }
  49. //Whatever happened, close the connection.
  50. $smtp->quit(true);