Thursday, February 12, 2009

Sending mail with PHP using msmtp

Msmtp is a very simple Mail-Transfer-Agent, which can be run on your local machine to send emails out, without the need to install sendmail or postfix. Many mutt users will currently use msmtp as their MTA.

To set up PHP to use msmtp (via the mail command):

Install msmtp. On Debian/Ubuntu machines you can simply: apt-get install mstmp

Create a .msmtprc file containing the following lines. Where ever you create this file, you'll need to make sure that it is readable by PHP (by the user that Apache is running as)


account default
host <smtp.server>
from <sender full email address>
domain <senders domain>


Modify the appropriate fields as necessary. The domain field is only required by some SMTP servers.

Make sure the file is owned by the user that Apache is running as (normally www-data) and that the permissions are set correctly. You may need to run these commands as root (or under sudo)

$ chown www-data .msmtprc
$ chmod 600 .msmtprc

Then, edit your php.ini, for me, it's located in /etc/php5/apache22/php.ini and change the sendmail_path configuration setting to:

sendmail_path = "/usr/bin/msmtp -C /path/to/.msmtprc -t"

And once you've restarted Apache (/usr/sbin/apache2ctl restart), you should be done, and you can test with:


<?
mail("your@email.com", "Test email from PHP", "If you can read this...");
?>