linux msmtp configuration sends from shell but fails from PHP/apache

Emily picture Emily · Sep 17, 2014 · Viewed 12.1k times · Source

linux (fedora 20) msmtp configuration sends from shell but fails from PHP/apache, I am stumped... my objective is just to send email, through my gmail smtp from my localhost development webserver, to test output of code that sends mail

php.ini sendmail file reads : sendmail_path = /usr/bin/msmtp --debug -C /etc/msmtprc --read-recipients

there is only one php.ini on the system, used for both CLI and webserver located at /etc/php.ini

permissions on /etc/msmtprc are set to apache:apache 600

the following commands as root work and produce a test email :

  • php -r "mail('[email protected]', 'Newest Test Email', 'Test email body');"
  • runuser -l apache -c '/usr/bin/msmtp --debug -C /etc/msmtprc --read-recipients < /var/www/html/test.mail' (test.mail includes to and from lines)

but apache/php produces an error when the php mail function is called from the following script:

if (mail('[email protected]', 'Newest Test Email', 'Test email body'))
print "Email successfully sent";
else
print "An error occured";

Log files during error read as follows :

  • /var/log/httpd/error_log : msmtp: cannot connect to smtp.gmail.com, port 587: Permission denied msmtp: could not send mail (account default from /etc/msmtprc)

/etc/msmtprc contains :

defaults
auth on
tls on
tls_trust_file /etc/pki/tls/cert.pem
account default
host smtp.gmail.com
port 587
user [email protected]
from [email protected]
password [******]
auth on
syslog on

any pointers in the correct direction are welcomed... only trying to achieve a simple avenue for localhost php mail function to send emails through my gmail smtp server - this is not a production server configuration, it is my local apache/php webserver for web development

Answer

SLC picture SLC · Mar 1, 2015

Sorry for the late reply. I also struggled with this issue my self. The problem was the file permissions on the configuration file.

If you remember correctly you we're asked to chmod the file to 0600 because it wouldn't work otherwise. And you probably created that file using a different user than the one of your web-server/php.

Which means that your web-server or the one controlling PHP cannot read that file to get your email configurations.

Also if you created your configuration file under ~/.msmtprc that also won't work. Because when used with PHP, MSMTP only uses the global one from /etc/msmtprc

Which means that you must create your config in /etc/msmtprc and then chown the configuration file to match the user of your webs-erver/php.

Since I was on Debian and I used NGINX I had to make that file accessible to www-data with chown www-data:www-data /etc/msmtprc On CentOS that user might be httpd So make sure you have that user set correctly.

After doing that I was able to send mails with MSMTP using PHP with no problems.