2.19.11. Checking outgoing mail via SMTP

To check the secure connection in line 34, replace mail.adm.tools on ssl://mail.adm.tools and 25 on 465.

flowchart LR Хостинг-аккаунт-->|Port 25|mail.adm.tools mail.adm.tools-->|Letter|Recipient

  1. Through filemanager or any FTPclient in root directory of the site create a file smtp_test.php with code like this:
    1. <?php
    2.  
    3. $login = 'from@example.com'; // вместо from@example.com укажите адрес созданного on хостинге почтового ящика
    4. $password = 'password'; // вместо password укажите password созданного on хостинге почтового ящика
    5. $to = 'to@example.com'; // вместо to@example.com укажите адрес получателя
    6.  
    7. $text = ""Hi, checking the SMTP connection.""; // содержимое отправляемого письма
    8.  
    9. // функция получения кода ответа сервера
    10. function get_data($smtp_conn) {
    11. $data = "";
    12. while ($str = fgets($smtp_conn, 515)) {
    13. $data .= $str;
    14. if (substr($str, 3, 1) == " ") {
    15. break;
    16. }
    17. }
    18. return $data;
    19. }
    20.  
    21. // формирование служебного заголовка письма
    22. $header = "Date: " . date("D, j M Y G:i:s") . " +0300\r\n";
    23. $header .= "From: =?UTF-8?Q?" . str_replace("+", "_", str_replace("%", "=", urlencode('Test script'))) . "?= <$login>\r\n";
    24. $header .= "X-Mailer: Test script hosting Ukraine.com.ua \r\n";
    25. $header .= "Reply-To: =?UTF-8?Q?" . str_replace("+", "_", str_replace("%", "=", urlencode('Test script'))) . "?= <$login>\r\n";
    26. $header .= "X-Priority: 3 (Normal)\r\n";
    27. $header .= "Message-ID: <12345654321." . date("YmjHis") . "@ukraine.com.ua>\r\n";
    28. $header .= "To: =?UTF-8?Q?" . str_replace("+", "_", str_replace("%", "=", urlencode('To the recipient of the test letter'))) . "?= <$to>\r\n";
    29. $header .= "Subject: =?UTF-8?Q?" . str_replace("+", "_", str_replace("%", "=", urlencode('examination'))) . "?=\r\n";
    30. $header .= "MIME-Version: 1.0\r\n";
    31. $header .= "Content-Type: text/plain; charset=UTF-8\r\n";
    32. $header .= "Content-Transfer-Encoding: 8bit\r\n";
    33.  
    34. $smtp_conn = fsockopen("mail.adm.tools", 25, $errno, $errstr, 10); // соединение с почтовым сервером mail.adm.tools через порт 25
    35. if (!$smtp_conn) { print ""The connection to the server failed""; fclose($smtp_conn); exit; }
    36. $data = get_data($smtp_conn);
    37.  
    38. fputs($smtp_conn, "EHLO ukraine.com.ua\r\n"); // начало приветствия
    39. $code = substr(get_data($smtp_conn), 0, 3); // examination, не вернул ли сервер ошибку
    40. if ($code != 250) { print ""EHLO welcome error""; fclose($smtp_conn); exit; }
    41.  
    42. fputs($smtp_conn, "AUTH LOGIN\r\n"); // начало процедуры авторизации
    43. $code = substr(get_data($smtp_conn), 0, 3);
    44. if ($code != 334) { print ""The server did not allow to start authorization""; fclose($smtp_conn); exit; }
    45.  
    46. fputs($smtp_conn, base64_encode("$login") . "\r\n"); // отправка логина от почтового ящика (on хостинге он совпадает с именем почтового ящика)
    47. $code = substr(get_data($smtp_conn), 0, 3);
    48. if ($code != 334) { print ""Error accessing this user""; fclose($smtp_conn); exit; }
    49.  
    50. fputs($smtp_conn, base64_encode("$password") . "\r\n"); // отправка пароля
    51. $code = substr(get_data($smtp_conn), 0, 3);
    52. if ($code != 235) { print ""Invalid password""; fclose($smtp_conn); exit; }
    53.  
    54. fputs($smtp_conn, "MAIL FROM:$login\r\n"); // отправка значения MAIL FROM
    55. $code = substr(get_data($smtp_conn), 0, 3);
    56. if ($code != 250) { print ""The server refused the MAIL FROM command""; fclose($smtp_conn); exit; }
    57.  
    58. fputs($smtp_conn, "RCPT TO:$to\r\n"); // отправка адреса получателя
    59. $code = substr(get_data($smtp_conn), 0, 3);
    60. if ($code != 250 AND $code != 251) { print ""The server did not accept the RCPT TO command""; fclose($smtp_conn); exit; }
    61.  
    62. fputs($smtp_conn, "DATA\r\n"); // отправка команды DATA
    63. $code = substr(get_data($smtp_conn), 0, 3);
    64. if ($code != 354) { print ""Server did not receive DATA""; fclose($smtp_conn); exit; }
    65.  
    66. fputs($smtp_conn, $header . "\r\n" . $text . "\r\n.\r\n"); // отправка тела письма
    67. $code = substr(get_data($smtp_conn), 0, 3);
    68. if ($code != 250) { print ""Error sending letter""; fclose($smtp_conn); exit; }
    69. if ($code == 250) { print ""The letter was sent successfully. Server response $code"; }
    70.  
    71. fputs($smtp_conn, "QUIT\r\n"); // завершение отправки командой QUIT
    72. fclose($smtp_conn); // закрытие соединения
    73. ?>

    Attention! Be sure to substitute in the script:

    • Instead from@example.comtitle mailbox.
    • Instead passwordpassword mailbox.
    • Instead to@example.com — recipient’s mail.
  2. Run the created script by accessing it through the browser at an address like example.com/smtp_test.php.
  3. Check for a test email in the recipient’s mailbox.

Important points:

  • To connect to your Gmail mailbox, use application password, not your Google account password.
  • The example script and library do not collect access data or Google account information.

flowchart LR Хостинг-аккаунт-->|Port 587|Gmail Gmail-->|Letter|Recipient

  1. Connect to hosting via SSH.
  2. Go to the site directory where the test script will be placed (instead of example.com/www enter your details):
    cd ~/example.com/www/
  3. Install PHPMailer library:
    composer require phpmailer/phpmailer
  4. Create application password to access your Gmail mailbox.
  5. Through filemanager or any FTPclient in root directory of the site create a file gmail_test.php with code like this:
    1. <?php
    2.  
    3. $login = 'from@gmail.com'; // вместо from@gmail.com укажите адрес вашего почтового ящика Gmail
    4. $password = 'app_password'; // вместо app_password specify the created application password
    5. $to = 'to@example.com'; // вместо to@example.com укажите адрес получателя
    6.  
    7. use PHPMailer\PHPMailer\PHPMailer;
    8. use PHPMailer\PHPMailer\SMTP;
    9. use PHPMailer\PHPMailer\Exception;
    10. require_once __DIR__ . '/vendor/phpmailer/phpmailer/src/Exception.php';
    11. require_once __DIR__ . '/vendor/phpmailer/phpmailer/src/PHPMailer.php';
    12. require_once __DIR__ . '/vendor/phpmailer/phpmailer/src/SMTP.php';
    13.  
    14. $mail = new PHPMailer(true);
    15. try {
    16. $mail->SMTPDebug = SMTP::DEBUG_SERVER;
    17. $mail->isSMTP();
    18. $mail->Host = 'smtp.gmail.com';
    19. $mail->SMTPAuth = true;
    20. $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    21. $mail->Port = 587;
    22. $mail->Username = $login;
    23. $mail->Password = $password;
    24. $mail->setFrom($login, 'Hosting.XYZ LTD user');
    25. $mail->addAddress($to, 'John Doe');
    26. $mail->addReplyTo($login, 'Hosting.XYZ LTD user');
    27. $mail->Subject = "Gmail SMTP test";
    28. $mail->Body = 'Hi, test Gmail SMTP connection';
    29. $mail->send();
    30. echo "Email message sent.";
    31. } catch (Exception $e) {
    32. echo "Error in sending email. Mailer Error: {$mail->ErrorInfo}";
    33. } finally {
    34. $mail->smtpClose();
    35. }
  6. Run the created script by accessing it through the browser at an address like example.com/gmail_test.php.
  7. Check for a test email in the recipient’s mailbox.
Content