Www data email php

PHP mail issue with www-data

It looks like [email protected] is your envelope «from» address. The envelope «from» address is different from the address that appears in your «From:» header of the email. It is what sendmail uses in its «MAIL FROM/RCPT TO» exchange with the receiving mail server.The main reason it is called an «envelope» address is that appears outside of the message header and body, in the raw SMTP exchange between mail servers.

The default envelope «from» address on unix depends on what sendmail implementation you are using. But typically it will be set to the username of the running process followed by «@» and the hostname of the machine. In a typical configuration this will look something like [email protected] .

If your emails are being rejected by receiving mail servers, or if you need to change what address bounce emails are sent to, you can change the envelope «from» address to solve your problems.

To change the envelope «from» address on unix, you specify an «-r» option to your sendmail binary. You can do this globally in php.ini by adding the «-r» option to the «sendmail_path» command line. You can also do it programmatically from within PHP by passing -r [email protected] as the additional parameter argument to the mail() function (the 5th argument). If you specify an address in both places, the sendmail binary will be called with two «-r» options, which may have undefined behavior depending on your sendmail implementation. With the Postfix MTA, later «-r» options silently override earlier options, making it possible to set a global default and still get sensible behavior when you try to override it locally.

Читайте также:  Php script tv show

EDIT

About optional flags that can be passed to sendmail: -f will set the From address, -r will override the default Return-path that sendmail generates (typically the From address gets used). If you want your bounce-backs to go to a different address than the from address, try using both flags at once: -f [email protected] -r [email protected]

my php.ini

[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 = ; 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 ; Log all mail() calls including the full path of the script, line #, to address and headers ;mail.log = 

Solution 2

Although this is an old question, I’m adding this answer in case it is of help to someone:

I had the same problem with the From: header being re-written to [email protected]. I eventually tracked it down to the ssmtp bridge service that was piping mail from our web server into our mailserver. I added the line FromLineOverride=YES in the file /etc/ssmtp/ssmtp.conf and the problem disappeared.

Solution 3

In my case, I’ve got a hosted server so I needed to edit this file :

Once done, personals headers are working.

Solution 4

I was having similar problem with www-data when all my mails were sent and received with this header:

I used the -f [email protected] flag as 5th argument with the PHP email() function (as mentioned in accepted answer), but i was still receiving my emails as:

So i added one more flag -f [email protected] -F info to set the full name of the email and finally i was getting emails as i wanted:

I’m posting this answer because nobody mentions it here and i got a little stuck on it.

Источник

PHP mail issue with www-data

If you’re experiencing issues sending mail with PHP and the www-data user, you’re not alone. This is a common issue that can be easily resolved with the following steps:

Step 1 – Check mail logs

The first thing you should do is check the mail logs to see if there are any error messages. To do this, you can run the following command:

sudo tail -f /var/log/mail.log 

This will allow you to see any errors that might be occurring when trying to send mail.

Step 2 – Check PHP mail settings

Next, you should check your PHP mail settings to make sure they are correct. Open your php.ini file and look for the following lines:

[mail function] ; For Win32 only. SMTP = localhost smtp_port = 25 ; For Unix only. sendmail_path = /usr/sbin/sendmail -t -i 

Make sure that the `sendmail_path` is set correctly. If you’re using Ubuntu, it should be set to `/usr/sbin/sendmail -t -i`.

Step 3 – Configure sendmail

Next, you need to configure sendmail to work with the www-data user. To do this, open the sendmail configuration file:

sudo nano /etc/mail/sendmail.conf 

Look for the following line:

DontBlameSendmail=GroupWritableDirPathSafe 
DontBlameSendmail=GroupReadableDirPathSafe 

Step 4 – Restart services

Finally, you need to restart the services to apply the changes:

sudo service apache2 restart sudo service sendmail restart 

Conclusion

By following the above steps, you should now be able to send mail with PHP using the www-data user. If you’re still experiencing issues, be sure to check the mail logs for any error messages.

Источник

How To Use Gmail or Yahoo with PHP mail() Function

How To Use Gmail or Yahoo with PHP mail() Function

The lines that the user needs to enter or customize will be in red in this tutorial!

The rest should mostly be copy-and-pastable.

About PHP mail()

The PHP mail() function uses the program in sendmail_path configuration directive to send emails. This is set up as sendmail by default.

While most Linux installations have sendmail preinstalled, there is always a hassle of setting up SPF/PTR records, generating DKIM keys and a lot more to ensure that the email sent by your PHP script is not flagged as spam. A SMTP client called MSMTP can be used to send emails using third-party SMTP servers, this can also be used by PHP’s mail() in the place of sendmail.

Installation

To install MSMTP on Fedora Linux use yum:

CentOS repository doesn’t have a RPM package for MSMTP so we need to install it from source:

yum install make gcc pkgconfig wget http://sourceforge.net/projects/msmtp/files/msmtp/1.4.31/msmtp-1.4.31.tar.bz2/download tar -xvf msmtp-1.4.31.tar.bz2 cd msmtp-1.4.31 ./configure make make install

The latest version is 1.4.31 at the time of this writing but it may change in future so to get the latest version, visit this sourceforge page.

On Ubuntu/Debian distribution use apt-get:

Configuring MSMTP

The configuration file of MSMTP is stored in ~/.msmtprc for each user and /etc/msmtprc is the system wide configuration file. Open the configuration file in your directory.

Add the following lines for a Yahoo account:

account yahoo tls on tls_starttls off tls_certcheck off auth on host smtp.mail.yahoo.com user user1 from user1@yahoo.com password yourYahooPa5sw0rd

For Gmail, use the following settings:

account gmail tls on tls_certcheck off auth on host smtp.gmail.com port 587 user user1@gmail.com from user1@gmail.com password yourgmailPassw0rd

This file can also have more than one account, just ensure that the «account» value is unique for each section. Save the file and use chmod to make this file readable only by the owner since it contains passwords. This step is mandatory because msmtp won’t run if the permissions are more than 600.

Before implementing this in PHP, check from the command-line to ensure it works properly. To do this, create a plain text file containing a simple email:

echo -e "From: alice@example.com \n\ To: bob@domain.com \n\ Subject: Hello World \n\ \n\ This email was sent using MSMTP via Gmail/Yahoo." >> sample_email.txt
cat sample_email.txt | msmtp --debug -a gmail bob@domain.com

Replace the word «gmail» with «yahoo» or whatever you entered for the «account» option. You’ll see a lot of messages because of the «—debug» parameter. This is to make troubleshooting easy if things don’t work as expected. If bob@domain.com receives this email, everything is setup correctly so copy this file to the /etc directory:

cp -p ~/.msmtprc /etc/.msmtp_php

Change the ownership to the username under which the web server is running. This can be «apache«, «www-data«, or «nobody» depending on the Linux distribution on your VPS and web server installed:

chown www-data:www-data /etc/.msmtp_php

Configuring PHP

Open the php.ini file, its location varies according to the OS and PHP type installed (PHP CGI, mod_php, PHP-FPM etc):

Modify it by adding the path to the msmtp command:

sendmail_path = "/usr/bin/msmtp -C /etc/.msmtp_php --logfile /var/log/msmtp.log -a gmail -t"

Manually create a log file and change its ownership to the username your web server is running as:

touch /var/log/msmtp.log chown www-data:www-data /var/log/msmtp.log

Restart your web server to apply the changes:

In Arch Linux, this is done using the systemctl command:

Depending on your OS and web server, replace «httpd» with the appropriate name. If PHP is running as a separate process (like PHP-FPM), restart it instead:

Create a PHP script with a simple mail() to test this setup:

receipient@domain.com","A Subject Here","Hi there,\nThis email was sent using PHP's mail function.")) print "Email successfully sent"; else print "An error occured"; ?>

Access this file from the web browser.

If this email wasn’t sent you can check the msmtp log file for errors.

Common errors

If the email was not sent when using the PHP script, troubleshoot as follows:

  • Check if you edited the correct php.ini file. This can be confirmed by creating a phpinfo(); file and checking the «Loaded Configuration File» section.
  • The path to the msmtp configuration file might be wrong or the web server doesn’t have permission to read this file.
  • Check if an email is sent by running the script using command-line PHP:

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Настройка 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 

Источник

Оцените статью