Настройка Sendmail для отправки почты без попадания в Спам
Столкнулся с проблемой: на правильно настроенном сервере Apache с установленными модулями и настроенными доменными записями у провайдера — письма отправленные через функцию mail из скриптов php попадали в спам или не доставлялись вовсе.
Начал разбираться и не смог найти не одной полноценной публикации в рунете, которая раскрывала бы проблему и помогала решить все вопросы.
Вашему вниманию представляю собранный из разных источников, проверенный и используемый способ настройки сервера для правильной отправки писем sendmail.
Система: Ubuntu 20.06
Почтовый сервис: Яндекс
1. Установка Sendmail
Если по какой-то причине не был установлен. Произведите базовую установку и настройку
sudo apt-get install php-mail sudo apt-get install sendmail sudo sendmailconfig
Вместо noreply@site.ru пишем почту на которую будут приходить отчеты (заголовок Return-Path:).
sendmail_path = "/usr/sbin/sendmail -t -f noreply@site.ru -i"
Заголовок «Return-Path:» является важным заголовком в глазах почтовых сервисов.
Если его не установить, заголовок будет равен примерно такому значению «Return-Path: ».
Очень желательно чтобы значение заголовка всегда совпадало с именем домена с которого отправляется письмо, независимо от значения заголовка «From:», иначе оно может быть отправлено в «Спам» или же отклонено вовсе.
2. Настройка DNS записей
Нам необходимо настроить SPF, DMARC, DKIM записи.
Какая за что отвечает расписывать не буду. В рунете огромное количество инструкций.
Если тоже используете какой-либо почтовый сервис, у них свои подробные инструкции по настройке.
На что следует обратить внимание — чтобы в SPF был прописан IP-адрес сервера.
v=spf1 ip4:ip_server include:_spf.yandex.net ~all
Затем следует запросить у провайдера DNS-хостинга обратную запись rDNS (PTR-запись).
Привязать свой домен к ip-адресу сервера.
Как правило провайдер самостоятельно ее устанавливает по запросу.
Установить hostname равный названию нашего домена:
sudo hostnamectl set-hostname site.ru
5. Редактировать файл sendmail.mc
Переходим к файлу /etc/mail/sendmail.mc
Нам необходимо настроить заголовки «Received: from» и «Received: by». Они являются важными при определении уровня доверия к серверу отправляющему электронную почту.
Добавляем следующие строки в конце файла перед MAILER_DEFINITIONS
FEATURE(allmasquerade) FEATURE(masquerade_envelope) FEATURE(local_no_masquerade) MASQUERADE_AS(`site.ru')
define(`MAIL_HUB', `site.ru.')dnl define(`LOCAL_RELAY', `site.ru.')dnl
6. Проверяем настройки apache и файервола
sudo ufw allow 25 sudo nano /etc/apache2/envvars
Ищем строчки и заменяем www-data на текущего пользователя под которым запущен apache
export APACHE_RUN_USER=www-data
export APACHE_RUN_GROUP=www-data
7. Обновляем конфигурацию и перезагружаем sendmail
sudo sendmailconfig sudo service sendmail restart sudo systemctl restart apache2
Sendmail php как настроить
Dibya Sahoo🥑
Published on 2019-10-16· Updated on 2021-12-15
The author voluntarily contributed this tutorial as a part of Pepipost Write to Contribute program.
Introduction
PHP comes with a default function mail() that allows you to sendmail directly from a PHP script. Here in this tutorial, we will be talking about the prerequisites to sending a mail directly from a PHP script, the syntax, and its parameters.
Prerequisites
- PHP4, PHP 5 or PHP 7
- PHP configured to sendmail. In case your PHP setup is not configured for sending email to the outside world, then please refer the steps mentioned at the end of this article.
Syntax
mail (to,subject,message,headers,parameters);
Parameters
to
String | Required
The email address of the recipient.
Note: The must comply with RFC 2822. You can pass one email address or multiple using comma-separated.
Few sample examples of how the values will look like:
subject
String | Required
The subject line of the email to be sent.
Note, the subject must comply with RFC 2047.
message
String | Required
The content of the mail that you want to send. Each line of the email should be separated with a CRLF (\r\n) and each line should not exceed 70 characters.
In case of Windows machine, when PHP is connecting to an SMTP server to sendmail, it removes a full stop which is found at the start of a line. To resolve this, replace the dot with a double dot, using the below code:
additional_headers
mixed (String or Array) | Optional
This parameter is used to pass any additional email headers like From, Cc and Bcc. Each additional headers should be separated with a CRLF (\r\n).
Note: While sending the email, make sure there is a From header. You can set the From header, either by using the additional_headers parameter or, you can also set a default value in php.ini.
additional_parameters
String | Optional
This additional_parameter can be used to pass additional flags to the Sendmail program as configured in the sendmail_path configuration setting. For example; you can use this parameter to set the envelope sender address when using Sendmail with -f option. PHP by default internally escape the values coming in this parameter with escapeshellcmd() to prevent any potential command execution.
Return Value
mail() function returns TRUE if the SMTP server successfully accepted the mail for delivery, else FALSE.
Getting TRUE doesn’t necessarily mean that the email is delivered to the recipient’s server. TRUE is just an indication that your mail has successfully submitted to the SMTP server’s queue for sending.
Returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise.
It is important to note that just because the mail was accepted for delivery, it does NOT mean the mail will reach the intended destination.
Note: mail() function will not work in Local server. A server connected to the internet and SMTP ports opened will be required to send mail.
Few Use Cases and Working Examples
1. How to send an HTML mail
[email protected], [email protected]"; $subject = "This is a test HTML email"; $message = "Test email. Please ignore.
"; // It is mandatory to set the content-type when sending HTML email $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; // More headers. From is required, rest other headers are optional $headers .= 'From: [email protected]>' . "\r\n"; $headers .= 'Cc: [email protected]' . "\r\n"; mail($to,$subject,$message,$headers); ?>
2. How to sendmail with an additional command line parameter.
As described above, for this use case, you need to use the additional_parameters parameter to pass an additional parameter to the program configured to used when sending mail using the sendmail_path.
[email protected]', 'This is a test subject line', 'The complete body of the message', null, '[email protected]'); ?>
Common Errors/Exceptions with PHP sendmail function
- Unable to send a large volume of emails using mail() function
Using a mail() function is not recommended for sending large volume emails, because it opens and closes an SMTP socket connection for each email. This is really not very efficient.
If you want to send a large amount of emails in PHP, then it is recommended to refer PEAR::Mail, and PEAR::Mail_Queue packages or use some good Email Service Provider which can help you scale your email volume. - Not receiving emails sent through PHP mail() function
While there can be N number of reason for the failure, but one the wried problem which many encounters is with the Unix mail transfer agents, which replace LF by CRLF automatically, which leads to doubling CR if CRLF is already used in your code. In such a case, try using an LF (\n) only. Read more about message format on RFC 2822. - Warning: mail(): «sendmail_from» not set in php.ini or custom «From:» header missing.
This error occurs mostly because while sending mail, you have not mentioned the From header using the additional_headers parameters.
Configuring PHP for sending mail
In order to configure anything related to PHP you need to change `php.ini` file. So, we will be editing php.ini file in order to configure Sendmail.
You can easily locate or search your php.ini file in Linux using below command:
The default location is `/etc/php.ini`
You can find the same in windows where XAMPP or LAMPP is installed:
`C:\xampp\php\php.ini`
Clarification:
Changing php.ini file to add mail configuration.
1. Open your php.ini file using below:
2. Search [mail function] in the file. It will be as shown below:
[mail function] ; For Win32 only. ; http://php.net/smtp SMTP = localhost ; http://php.net/smtp-port smtp_port = 25 ; For Win32 only. ; http://php.net/sendmail-from ;sendmail_from = [email protected] ; For Unix only. You may supply arguments as well (default: "sendmail -t -i"). ; http://php.net/sendmail-path sendmail_path = /usr/sbin/sendmail -t -i ; Force the addition of the specified parameters to be passed as extra parameters ; to the sendmail binary. These parameters will always replace the value of ; the 5th parameter to mail(), even in safe mode. ;mail.force_extra_parameters = ; Add X-PHP-Originating-Script: that will include uid of the script followed by the filename mail.add_x_header = On ; The path to a log file that will log all mail() calls. Log entries include ; the full path of the script, line number, To address and headers. ;mail.log =
3. Add your mail server details to the file or incase you have one you can change it (mail server can be your own ie. local mail server or you can use any ESP as a mail server).
For Linux/Mac OS:
— Check for `sendmail_path` and ensure; is not (semicolon is used to show the line is commented).
— By default it will use `/usr/bin/sendmail -t -i` you can change it if you are using any custom path.For Window:
— Check for `SMTP = localhost` and change it to your desired mail server (any ESP or localhost) no changes are required if you are using your own local server.
— Or you can also use the smtp server of any Email Service Provider like Pepipost, Sendgrid, Mailgun, Sparkpost.
4. Save/close the php.ini file
5. The final step, don’t forget to restart your webserver/php-fpm.
Pro tip: You can host a simple “info.php” on your webserver to check each and every configuration of your PHP using below 2 liner code:
Save and exit the file.
6. Reload you webserver and php-fpm.
7. Hit http://localhost/php_info.php on your web browser.
Conclusion
Hope, this tutorial is able to help you send mail using PHP.
In case you are facing some issues which are not listed above in the tutorial, or you have some suggestions, then please feel free to contribute below in comments.
Grade My Email
Check your spam now?
Netcorecloud’s toolkit is the solution to all your email problems.