2.24.11. Checking the operation of outgoing mail via SMTP

  1. Build with filemanager or any FTPclient in root directory site file test.php with code like this:
    <?php
     
    $login = 'test@example.com'; // замените test@example.com на адрес электронной почты, с которого производится отправка (поскольку логин совпадает с адресом отправителя - данная переменная используется и как логин, и как адрес отправителя)
    $password = 'password'; // замените password на password от почтового ящика, с которого производится отправка
    $to = 'to@example.com'; // замените to@example.com на адрес электронной почты получателя письма
     
    $text = "Hi, checking the SMTP connection."; // содержимое отправляемого письма
     
    // функция получения кода ответа сервера
    function get_data($smtp_conn) {
        $data = "";
        while ($str = fgets($smtp_conn, 515)) {
            $data .= $str;
            if (substr($str, 3, 1) == " ") {
                break;
            }
        }
        return $data;
    }
     
    // формирование служебного заголовка письма
    $header = "Date: " . date("D, j M Y G:i:s") . " +0300\r\n";
    $header .= "From: =?UTF-8?Q?" . str_replace("+", "_", str_replace("%", "=", urlencode('Test script'))) . "?= <$login>\r\n";
    $header .= "X-Mailer: Test script hosting Ukraine.com.ua \r\n";
    $header .= "Reply-To: =?UTF-8?Q?" . str_replace("+", "_", str_replace("%", "=", urlencode('Test script'))) . "?= <$login>\r\n";
    $header .= "X-Priority: 3 (Normal)\r\n";
    $header .= "Message-ID: <12345654321." . date("YmjHis") . "@ukraine.com.ua>\r\n";
    $header .= "To: =?UTF-8?Q?" . str_replace("+", "_", str_replace("%", "=", urlencode('To the recipient of the test letter'))) . "?= <$to>\r\n";
    $header .= "Subject: =?UTF-8?Q?" . str_replace("+", "_", str_replace("%", "=", urlencode('проверка'))) . "?=\r\n";
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: text/plain; charset=UTF-8\r\n";
    $header .= "Content-Transfer-Encoding: 8bit\r\n";
     
    $smtp_conn = fsockopen("mail.adm.tools", 25, $errno, $errstr, 10); // соединение с почтовым сервером mail.ukraine.com.ua через порт 25
    if (!$smtp_conn) { print "The connection to the server failed"; fclose($smtp_conn); exit; }
    $data = get_data($smtp_conn);
     
    fputs($smtp_conn, "EHLO ukraine.com.ua\r\n"); // начало приветствия
    $code = substr(get_data($smtp_conn), 0, 3); // проверка, не вернул ли сервер ошибку
    if ($code != 250) { print "EHLO welcome error"; fclose($smtp_conn); exit; }
     
    fputs($smtp_conn, "AUTH LOGIN\r\n"); // начало процедуры авторизации
    $code = substr(get_data($smtp_conn), 0, 3);
    if ($code != 334) { print "The server did not allow to start authorization"; fclose($smtp_conn); exit; }
     
    fputs($smtp_conn, base64_encode("$login") . "\r\n"); // отправка логина от почтового ящика (на хостинге он совпадает с именем почтового ящика)
    $code = substr(get_data($smtp_conn), 0, 3);
    if ($code != 334) { print "Error accessing this user"; fclose($smtp_conn); exit; }
     
    fputs($smtp_conn, base64_encode("$password") . "\r\n"); // отправка пароля
    $code = substr(get_data($smtp_conn), 0, 3);
    if ($code != 235) { print "Invalid password"; fclose($smtp_conn); exit; }
     
    fputs($smtp_conn, "MAIL FROM:$login\r\n"); // отправка значения MAIL FROM
    $code = substr(get_data($smtp_conn), 0, 3);
    if ($code != 250) { print "The server refused the MAIL FROM command"; fclose($smtp_conn); exit; }
     
    fputs($smtp_conn, "RCPT TO:$to\r\n"); // отправка адреса получателя
    $code = substr(get_data($smtp_conn), 0, 3);
    if ($code != 250 AND $code != 251) { print "The server did not accept the RCPT TO command"; fclose($smtp_conn); exit; }
     
    fputs($smtp_conn, "DATA\r\n"); // отправка команды DATA
    $code = substr(get_data($smtp_conn), 0, 3);
    if ($code != 354) { print "Server did not receive DATA"; fclose($smtp_conn); exit; }
     
    fputs($smtp_conn, $header . "\r\n" . $text . "\r\n.\r\n"); // отправка тела письма
    $code = substr(get_data($smtp_conn), 0, 3);
    if ($code != 250) { print "Error sending letter"; fclose($smtp_conn); exit; }
    if ($code == 250) { print "The letter was sent successfully. Server response $code"; }
     
    fputs($smtp_conn, "QUIT\r\n"); // завершение отправки командой QUIT
    fclose($smtp_conn); // закрытие соединения
    ?>

    Attention! Be sure to substitute in the script:

    • Instead test@example.comtitle mailbox.
    • Instead passwordpassword mailbox.
    • Instead to@example.com - the name of the recipient's mailbox.
  2. Run the created script by accessing it through the browser at an address like www.your.site/test.php.
  3. In the mailbox specified instead of to@example.com, check for the presence of a letter that the test script should have sent.

Important points:

  • Gmail accounts have different security systems that can interfere with the connection to the Google SMTP server. For the test script to work, you must at least: disable two-step authentication, and allow connecting to the account of unreliable applications. For the script to work correctly, additional actions with account security settings may also be required.
  • The script and library from the example do not collect access data and account information.
  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. Disable 2-Step Verification with your Google Account. Without this, the SMTP connection will not work.
  5. Allow connecting to the account of unreliable applications. Without this, the SMTP connection will not work.
  6. Build with filemanager or any FTPclient in root directory site file test.php with code like this:
    <?php
     
    $login    = 'test@gmail.com'; // замените test@gmail.com на адрес электронной почты, с которого производится отправка (поскольку логин совпадает с адресом отправителя - данная переменная используется и как логин, и как адрес отправителя)
    $password = 'password'; // замените password на password от почтового ящика, с которого производится отправка
    $to       = 'to@example.com'; // замените to@example.com на адрес электронной почты получателя письма
     
    use PHPMailer\PHPMailer\PHPMailer; 
    use PHPMailer\PHPMailer\SMTP; 
    use PHPMailer\PHPMailer\Exception;
    require_once __DIR__ . '/vendor/phpmailer/phpmailer/src/Exception.php'; 
    require_once __DIR__ . '/vendor/phpmailer/phpmailer/src/PHPMailer.php'; 
    require_once __DIR__ . '/vendor/phpmailer/phpmailer/src/SMTP.php';
     
    $mail = new PHPMailer(true);
    try {
        $mail->SMTPDebug = SMTP::DEBUG_SERVER;
        $mail->isSMTP();
        $mail->Host = 'smtp.gmail.com';
        $mail->SMTPAuth = true;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port = 587;
        $mail->Username = $login;
        $mail->Password = $password;
        $mail->setFrom($login, 'Hosting.XYZ LTD user');
        $mail->addAddress($to, 'John Doe');
        $mail->addReplyTo($login, 'Hosting.XYZ LTD user');
        $mail->Subject = "Gmail SMTP test";
        $mail->Body = 'Hi, test Gmail SMTP connection';
        $mail->send();
        echo "Email message sent.";
    } catch (Exception $e) {
        echo "Error in sending email. Mailer Error: {$mail->ErrorInfo}";
    } finally {
        $mail->smtpClose();
    }

    Attention! Be sure to substitute in the script:

    • Instead test@gmail.comtitle mailbox.
    • Instead passwordpassword mailbox.
    • Instead to@example.com - the name of the recipient's mailbox.
  7. Run the created script by accessing it through the browser at an address like www.your.site/test.php.
  8. In the mailbox specified instead of to@example.com, check for the presence of a letter that the test script should have sent.
Content