smtp_check.phps 2.0 KB

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