Bitrix does not send mail or gets into spam
Rus
Eng
Битрикс не отправляется почта или попадает в спам
I solve complex technical challenges for Bitrix and 1C—ranging from auditing existing code to website development and configuring complex integrations—with a guarantee of results.
Recommended

Website hosting

If you are choosing hosting for your project, I recommend Reg.ru. Modern infrastructure, a wide range of plans from starter options to high-load VPS, and responsive tech support that actually helps instead of sending template replies. I host some of my own projects there and recommend it to my clients.

Go to site Affiliate link. The price remains the same for you.

All English-language materials have been translated fully automatically using the Google service

Testing Email Delivery

Sending a Test Email from the Console

echo "Test text" | mail -s "Test title" info@domain.ru

Checking the mail Function from the Bitrix PHP Console

if (mail("info@domain.ru", "Subject", "Text")) {
    echo 'Sent successfully!';
} else {
    echo 'Delivery failed!';
}

Checking Sockets

$fp = fsockopen("ssl://smtp.mail.ru", 465, $errno, $errstr, 30);
if (!$fp) {
    echo "Error: $errstr ($errno)\n";
} else {
    echo "Connected";
}
fclose($fp);

Correct msmtp Config and App Password

If you're sure the config is correct but emails still aren't going out, the cause is most likely the need to use an app password.

Let's check and send a test email from the console with detailed logging. Don't forget to replace domain.ru with your own domain.

echo -e "To: info@domain.ru\nSubject: Test from msmtp\n\nThis is a test message." | msmtp --debug -a default info@domain.ru

If the config is set up correctly, you'll likely see this (or a similar) error in the response:

535 5.7.0 NEOBHODIM parol prilozheniya https://help.mail.ru/mail/security/protection/external / Application password is REQUIRED

This means an app password is required. Mail services have moved to a higher security level and require an app password rather than the regular mailbox password. How to create one — see your mail service's documentation.

This applies to all major mail service providers on the market. Each has its own terms and pricing, though.

But even if you've already issued an app password, emails may still fail. For example, Mail.ru disabled email sending via SMTP for external services on free plans in mid-2026. You can switch to a paid plan — but personally I prefer a quality free service.

Note: a free alternative to SMTP mail sending services

If you've hit authorization errors when sending mail via smtp.mail.ru (e.g., 535 5.7.0 NEOBHODIM parol prilozheniya) and standard fixes don't help — take a look at the alternative service smtp.bz.

It lets you send up to 500 emails per day for free, is simple to set up, and doesn't require app passwords. Just specify host, port, user, and password from the service's dashboard in your msmtp config.

Works both for BitrixVM and other systems using SMTP sending. Affiliate link, the price stays the same for you.

Checking Bitrix Settings

Go to Settings > Product Settings > Email and SMS Events > Email Templates and review the templates. Make sure the From field contains #DEFAULT_EMAIL_FROM#.

Go to Settings > Product Settings > Module Settings > Main Module > Email and SMS and set the correct sender address in the Site Administrator Email (default sender) field.

Just in case, you can also set the email in the Sales Department E-Mail: field under Settings > Product Settings > Module Settings > e-Store > Settings.

The email must match in all listed places, plus msmtp must use exactly that address.

msmtp Config Examples for Simple Sending

Via mail.ru

account default
logfile /home/bitrix/.msmtp.log
host mail.bitrixsoft.com
port 25
from info@domain.ru
auth off

Via smtp.bz

account default
logfile /home/bitrix/msmtp_default.log
host connect.smtp.bz
port 587
from info@domain.ru
keepbcc off
auth on
user info@domain.ru
password PASSWORD
tls on
tls_certcheck off

Via smtp.mail.ru

account default
logfile /home/bitrix/msmtp_default.log
host smtp.mail.ru
port 587
from info@domain.ru
keepbcc off
auth on
user info@domain.ru
password PASSWORD
tls on
tls_starttls on
tls_certcheck off

Via smtp.yandex.ru

account default
logfile /var/log/msmtp.log
host smtp.yandex.ru
port 587
from info@domain.ru
keepbcc on
auth on
user info@domain.ru
password PASSWORD
tls on
tls_starttls on

Via smtp.gmail.com

account default
tls on
tls_certcheck off
auth on
host smtp.gmail.com
port 587
user info@domain.ru
from info@domain.ru
password PASSWORD

Via smtp.timeweb.ru

# smtp account configuration for default
account default
logfile /home/bitrix/msmtp_default.log
host smtp.timeweb.ru
port 465
from info@domain.ru
aliases /etc/aliases
keepbcc off
auth on
user info@domain.ru
password PASSWORD

tls on
tls_starttls off
tls_certcheck off

Getting the Email List

SELECT * FROM b_event
WHERE event_name LIKE 'SALE_NEW_ORDER'
ORDER BY date_insert DESC

Send Status Values in the SUCCESS_EXEC Column

'Y'         — sent successfully;
'N' or 0    — not sent;
'F'         — error

Attaching a File to a Standard Bitrix Email Template

$FILES = [];
foreach ($_FILES as $file) {
    if (!empty($file['tmp_name'])) {
        $FILES[] = CFile::SaveFile($file);
    }
}

CEvent::Send('SUBSCRIBE_CONFIRM', SITE_ID, $eventFields, 'Y', '', $FILES);

SMTP Debug Script

// Connection settings
$smtp_host = 'smtp.yandex.ru';
$smtp_port = 587; // Usually 587 for TLS/STARTTLS or 465 for SSL
$smtp_user = 'info@domain.ru';
$smtp_pass = 'PASSWORD';
$timeout   = 10;

function parse_smtp_response($stream, $expected_code) {
    $response = '';
    while ($line = fgets($stream, 515)) {
        $response .= $line;
        // If the 4th char is a space, this is the last line of the server response
        if (isset($line[3]) && $line[3] == ' ') {
            break;
        }
    }

    $code = substr($response, 0, 3);
    if ($code != $expected_code) {
        throw new Exception("Unexpected server response: " . trim($response));
    }
    return $response;
}

try {
    // Connect to the server
    $socket = stream_socket_client("tcp://$smtp_host:$smtp_port", $errno, $errstr, $timeout);
    if (!$socket) {
        throw new Exception("Connection error ($errno): $errstr");
    }

    // Read the greeting (expect code 220)
    parse_smtp_response($socket, '220');

    // Greet the server (EHLO)
    fwrite($socket, "EHLO localhost\r\n");
    parse_smtp_response($socket, '250');

    // Enable STARTTLS for port 587
    // If you connected directly to port 465, skip this step
    fwrite($socket, "STARTTLS\r\n");
    parse_smtp_response($socket, '220');

    // Enable encryption on the existing stream
    if (!stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
        throw new Exception("Failed to start TLS encryption.");
    }

    // Re-greet EHLO inside the secure channel
    fwrite($socket, "EHLO localhost\r\n");
    parse_smtp_response($socket, '250');

    // AUTH LOGIN
    fwrite($socket, "AUTH LOGIN\r\n");
    parse_smtp_response($socket, '334'); // Server asks for login

    // Send login in Base64
    fwrite($socket, base64_encode($smtp_user) . "\r\n");
    parse_smtp_response($socket, '334'); // Server asks for password

    // Send password in Base64
    fwrite($socket, base64_encode($smtp_pass) . "\r\n");
    parse_smtp_response($socket, '235'); // Code 235 means successful login!

    echo "Success! SMTP connection and authentication went through correctly.";

    // Close the session
    fwrite($socket, "QUIT\r\n");
    fclose($socket);
} catch (Exception $e) {
    echo "SMTP check error: " . $e->getMessage();
    if (isset($socket) && is_resource($socket)) {
        fclose($socket);
    }
}

Sending Mail via phpMailer

Install composer:

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('sha384', 'composer-setup.php') === 'e0012edf3e80b6978849f5eff0d4b4e4c79ff1609dd1e613307e16318854d24ae64f26d17af3ef0bf7cfb710ca74755a') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"

Install phpMailer:

composer require phpmailer/phpmailer

If the composer command isn't found, install it globally:

curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer

Add to init.php:

require '/var/www/YOUR_SITE/vendor/autoload.php';

use Bitrix\Main\Application;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Intercept email event generation with the ability to cancel it
AddEventHandler("main", "OnBeforeEventAdd", array("OnBeforeEventAddClass", "OnBeforeEventAddHandler"));
class OnBeforeEventAddClass
{
    function OnBeforeEventAddHandler(&$event, &$lid, &$arFields, &$message_id, &$files)
    {
        $connection = Bitrix\Main\Application::getConnection('default'); // Get the database connection

        // Get the email template
        $recordset = $connection->query("select SUBJECT, MESSAGE, MESSAGE_PHP from b_event_message where ACTIVE = 'Y' AND EVENT_NAME = '" . $event . "'")->fetchAll();
        $fields = $arFields;

        AddMessage2Log($arFields, "arFields");

        if (isset($recordset[0]['MESSAGE'])) { // Check if the template exists
            $mask = $recordset[0]['MESSAGE'];
            $subject = $recordset[0]['SUBJECT'];

            foreach ($fields as $key => $value) {
                if (!is_array($value) && strpos($key, '~') === false) { // Skip arrays and ~ symbols
                    // Replace all possible patterns
                    $mask = preg_replace('~\#' . $key . '\#~', $value, $mask);
                    $subject = preg_replace('~\#' . $key . '\#~', $value, $subject);
                }
            }

            $mask = preg_replace('~\#SITE_NAME\#~', COption::GetOptionString("main", "site_name", $GLOBALS["SERVER_NAME"]), $mask);
            $mask = preg_replace('~\#SERVER_NAME\#~', COption::GetOptionString("main", "server_name", $GLOBALS["SERVER_NAME"]), $mask);
            $mask = preg_replace('~\#DEFAULT_EMAIL_FROM\#~', COption::GetOptionString("main", "email_from", "info@domain.ru"), $mask);

            $subject = preg_replace('~\#SITE_NAME\#~', COption::GetOptionString("main", "server_name", $GLOBALS["SERVER_NAME"]), $subject);
            $subject = preg_replace('~\#SERVER_NAME\#~', COption::GetOptionString("main", "server_name", $GLOBALS["SERVER_NAME"]), $subject);

            if ($mask) { // If the body is composed, start sending
                if (isset($fields['RS_USER_EMAIL'])) {
                    if (filter_var($fields['RS_USER_EMAIL'], FILTER_VALIDATE_EMAIL)) {
                        $email = $fields['RS_USER_EMAIL'];
                    }
                }

                if (isset($fields['EMAIL'])) {
                    if (filter_var($fields['EMAIL'], FILTER_VALIDATE_EMAIL)) {
                        $email = $fields['EMAIL'];
                    }
                }

                if (isset($fields['EMAIL_RAW'])) {
                    if (filter_var($fields['EMAIL_RAW'], FILTER_VALIDATE_EMAIL)) {
                        $email = $fields['EMAIL_RAW'];
                    }
                }

                if (isset($fields['EMAIL_BUYER'])) {
                    if (filter_var($fields['EMAIL_BUYER'], FILTER_VALIDATE_EMAIL)) {
                        $email = $fields['EMAIL_BUYER'];
                    }
                }

                if (isset($fields['EMAIL_TO'])) {
                    if (filter_var($fields['EMAIL_TO'], FILTER_VALIDATE_EMAIL)) {
                        $email = $fields['EMAIL_TO'];
                    }
                }

                if (!$email) {
                    $email = 'info@domain.ru';
                }

                if ($email && filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    $cl = new OnBeforeEventAddClass;
                    if ($cl->custom_mail($email, $subject, $mask, '', '')) { // Send the email
                        // AddMessage2Log($event, "Message was sent");
                    } else {
                        // AddMessage2Log($event, "Error. Message was not sent");
                    }
                } else {
                    // AddMessage2Log($event, "Error. Email not found");
                }

                return false;
            } else {
                // AddMessage2Log($event, "Error. No email body");
            }
        } else {
            // AddMessage2Log($event, "Error. Email template not found");
        }
    }

    public function custom_mail($to, $subject, $message, $additionalHeaders = '', $additional_parameters)
    {
        // Instantiation and passing `true` enables exceptions
        $mail = new PHPMailer(true);

        $mail->IsSMTP(true);    // enable SMTP
        $mail->SMTPDebug = 3;   // debugging: 1 = errors and messages, 2 = messages only
        $mail->SMTPAuth = true; // authentication enabled
        $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
        $mail->Host = 'smtp.gmail.com';
        $mail->Port = 465;      // set the SMTP port for the GMAIL server

        $mail->Username = 'info@domain.ru'; // SMTP username
        $mail->Password = 'PASSWORD';       // SMTP password

        $mail->CharSet = 'UTF-8';

        $mail->addAddress($to);
        $mail->setFrom('info@domain.ru');

        // Set the subject line
        $mail->Subject = $subject;

        // Read an HTML message body from an external file, convert referenced images to embedded,
        // convert HTML into a basic plain-text alternative body
        $mail->msgHTML($message);

        // Replace the plain text body with one created manually
        $mail->AltBody = 'This is a plain-text message body';

        $d_message = '';
        // preg_match('/From: (.+)\n/i', $additionalHeaders, $matches);
        // list(, $from) = $matches;
        $from = 'info@domain.ru';
        $d_message .= '$from - ' . $from . ' +++ ';
        $d_message .= '$to - ' . $to . ' +++ ';
        $d_message .= '$subject - ' . $subject . ' +++ ';
        $d_message .= '$message - ' . $message . ' +++ ';
        $mail->setFrom($from);
        $mail->addAddress($to, ''); // Add a recipient

        // $mail->addReplyTo($from, '');
        // $mail->AddBCC($from);
        // $mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
        // $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name

        $mail->Subject = $subject;

        if ($message != strip_tags($message)) {
            $mail->isHTML(true);
        }

        $mail->Body = $message;
        // $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

        if (!$mail->send()) {
            AddMessage2Log($mail->ErrorInfo, "Mailer Error");
            return false;
        } else {
            return true;
        }
    }
}

// Intercept the email right before sending
AddEventHandler('main', 'OnBeforeEventSend', Array("OnBeforeEventSendClass", "my_OnBeforeEventSend"));
class OnBeforeEventSendClass
{
    function my_OnBeforeEventSend($arFields, $arTemplate)
    {
        // get the message
    }
}

To send mail via phpMailer through smtp.mail.ru, the config should look like this:

$mail = new \PHPMailer\PHPMailer\PHPMailer(true);

$mail->IsSMTP(true);    // enable SMTP
$mail->SMTPDebug = 1;   // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = 'ssl://smtp.mail.ru';
$mail->Port = 465;      // set the SMTP port for the GMAIL server

$mail->Username = 'info@domain.ru'; // SMTP username
$mail->Password = 'PASSWORD';       // SMTP password

Debugging via AddMessage2Log

In dbconn.php, add the line:

define("LOG_FILENAME", $_SERVER["DOCUMENT_ROOT"] . "/log.txt");

cannot connect to localhost, port 25: Connection refused

After installing a clean Битрикс environment, this error is quite common. To fix it — use postfix:

yum install postfix
service postfix start
chkconfig postfix on

the server sent an empty reply in the msmtp log

Add to the config:

tls_starttls off

Troubleshooting

SMTP connect() failed When Sending via Google

If you're trying to send mail via Google SMTP and get an error like <

Aleksandr Tichiy
Author

Aleksandr Tichiy

Fullstack developer · 1C-Bitrix

I build and modernize online stores and corporate portals on 1C-Bitrix. Integrations with 1C, high-load performance, 152-FZ compliance. Writing about architecture and e-commerce.


Comments

There are no comments yet, you can be the first to leave it

Leave a comment

The site uses a comment pre-moderation system, so your message will be published only after approval by the moderator

You are replying to a user's comment

Send

FEEDBACK

Email me

Please message me to discuss the task. I work remotely and officially (as a self-employed professional); my hourly rate is 1,800 RUB, and I can dedicate 3–4 hours a day to the project. I respond quickly, and the consultation is free.

An error occurred while sending, please try again after a while
Message sent successfully

Phones

+7(993) 007-18-96

Email

info@tichiy.ru

Address

Россия, г. Москва

By submitting the form, you automatically confirm that you have read and accept the Privacy Policy site