Bitrix does not send mail or gets into spam
Rus
Eng
Битрикс не отправляется почта или попадает в спам

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

Testing sending emails

Sending a test email from the console

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

Checking the operation of the mail function from the PHP Bitrix console

if( mail("test@test.ru", "Subject", "Text") ){
	echo 'Успешно отправлено!'; }
else{
	echo 'Отправка не удалась!';
}

Checking socket operation

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

Checking Bitrix settings

Go to Settings> Product Settings> Mail & SMS Events> Mail Templates and browse through the templates. Make sure that the From field contains #DEFAULT_EMAIL_FROM#

Go to Settings> Product settings> Modules settings> Main module> Mail and SMS in the Email of the site administrator (default sender) enter the correct value of the sender's mail

Just in case, you can also specify mail in the E-Mail field of the sales department: along the path Settings> Product settings> Module settings> Online store> Settings

Email must match in all of the above cases, plus it must be specified in the msmtp settings

msmtp config for simple submission via mail.ru

account default
logfile /home/bitrix/.msmtp.log
host mail.bitrixsoft.com
port 25
from user@email.com
auth off

msmtp config for simple submission via smtp mail.ru

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

msmtp config for simple submission via smtp yandex.ru

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

msmtp config for easy submission via smtp gmail.com

account default
tls on
tls_certcheck off
auth on
host smtp.gmail.com
port 587
user usr@gmail.com
from usr@gmail.com
password yourgmailPass

msmtp config for easy shipping via smtp timeweb.ru

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

tls on
tls_starttls off
tls_certcheck off

Getting the list of letters

select * from b_event
where event_name like 'SALE_NEW_ORDER'
order by date_insert desc

Values of the status of sending letters in the column SUCCESS_EXEC

‘Y’ — означает успешная отправка;
‘N’ или 0 — письмо не отправлено;
‘F’ — ошибка

How to attach 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);

Script for 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');"

Installing phpMailer

composer require phpmailer/phpmailer

If the composer command is not found, then we try to 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;

//Перехват генерации почтового события с возможностью его отмены
AddEventHandler("main", "OnBeforeEventAdd", array("OnBeforeEventAddClass", "OnBeforeEventAddHandler"));
class OnBeforeEventAddClass
{
    function OnBeforeEventAddHandler(&$event, &$lid, &$arFields, &$message_id, &$files)
    {
        $connection = Bitrix\Main\Application::getConnection('default');//Получаем соединение с БД

        //Получаем шаблон письма
        $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'])){//Проверяем есть ли шаблон
            $mask = $recordset[0]['MESSAGE'];
            $subject = $recordset[0]['SUBJECT'];

            foreach ($fields as $key => $value){
                if(!is_array($value) && strpos($key, '~') === false){//Исключаем из замены массивы и символы ~
                    //Заменяем все возможные паттерны
                    $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", "admin@".$GLOBALS["SERVER_NAME"]), $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(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 = 'default@email.ru';
                }

                if($email && filter_var($email, FILTER_VALIDATE_EMAIL)){
                    $cl = new OnBeforeEventAddClass;
                    if($cl->custom_mail($email, $subject, $mask,'','')){//Отправляем письмо
                        //AddMessage2Log($event, "Сообщение было отправлено");
                    }else{
                        //AddMessage2Log($event, "Ошибка. Сообщение отправлено не было");
                    }
                }else{
                    //AddMessage2Log($event, "Ошибка. Почта не найдена. Почта:");
                }

                return false;

            }else{
                //AddMessage2Log($event, "Ошибка. Нет тела письма");
            }
        }else{
            //AddMessage2Log($event, "Ошибка. Не найден шаблон письма");
        }

    }

    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 = 'email'; // SMTP username
        $mail->Password = 'password'; // SMTP password

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

        $mail->addAddress($to);
        $mail->setFrom('default@email.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 = 'admin@YOUR_SITE';
        $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;
        }
    }
}


//Перехват письма непосредственно перед отправкой
AddEventHandler('main', 'OnBeforeEventSend', Array("OnBeforeEventSendClass", "my_OnBeforeEventSend"));
class OnBeforeEventSendClass
{
    function my_OnBeforeEventSend($arFields, $arTemplate)
    {

        //получим сообщение

    }
}

To send emails using phpMailer via 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 = 'USER_NAME'; // SMTP username
$mail->Password = 'USER_PASSWORD'; // SMTP password

Debug with AddMessage2Log

In the dbconn.php file, add the line define ("LOG_FILENAME", $ _SERVER ["DOCUMENT_ROOT"]. "/ log.txt");

the server sent an empty reply in the log msmtp

Add to configг

tls_starttls off

cannot connect to localhost, port 25: Connection refused

After installing a clean Bitrix environment, I often see this error. To fix - use postfix

yum install postfix
service postfix start
chkconfig postfix on

Dealing with bugs

If you are trying to send mail via smtp by Google and you get an error like SMTP connect () failed , then go to your Google account from which sending mail. Open the settings, go to the Security tab, find the item "Unreliable applications that have access to your account", go to it and allow access to unsafe applications ( link )

Fighting the Mail command not found

error
yum install sendmail
yum -y install mailx
service sendmail start

Transfer of agents to CZK

Editing the file /bitrix/php_interface/dbconn.php

Sometimes you need to comment out the cron support connection strings

define('BX_CRONTAB', true);
define('BX_CRONTAB_SUPPORT', true);

Go to Preferences> Tools> PHP Command Line and execute the following code:

COption::SetOptionString("main", "agents_use_crontab", "Y");
echo COption::GetOptionString("main", "agents_use_crontab", "N");

Let's open the crones settings

crontab -u bitrix -e или crontab -e

Let's add an entry:

*/1 * * * *  php -f /home/bitrix/www/bitrix/modules/main/tools/cron_events.php >/dev/null 2>&1

Restarting cron

systemctl restart crond.service

The cron settings are well described in documentation

& nbsp;

You can study the issue in more detail in the official documentation:

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

Are you developing a new service, making improvements to the existing one and want to be better than your competitors? You have come to the right place. I offer you a comprehensive studio-level website development. From me you can order design, layout, programming, development of non-traditional functionality, implementation of communication between CMS, CRM and Data Analitics, as well as everything else related to sites, except for promotion.

Contact, I will always advise on all questions and help you find the most effective solution for your business. I am engaged in the creation of sites in Novosibirsk and in other regions of Russia, I also work with the CIS countries. You will be satisfied with our cooperation

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

Contact with me
Send message
By submitting the form, you automatically confirm that you have read and accept Privacy policy of site
Sending successful!
Thank you for contacting :) I will contact you as soon as possible
Sending failed
An error occurred while sending the request. Please wait and try again after a while or call my phone number