Enable PHP Mail on OS X Mountain Lion

Support this website by purchasing prints of my photographs! Check them out here.
DEPRECATED: This post may no longer be relevant or contain industry best-practices.

I recently tried using the PHP mail() function on my OS X Mountain Lion installation, but was greeted with some errors instead of a successful email. I'm not sure why the mail function stopped working after upgrading to Mountain Lion, but it appears to be some sort of permissions issue.

To fix the issue, execute the following commands:

sudo mkdir -p /Library/Server/Mail/Data/spool
sudo /usr/sbin/postfix set-permissions
sudo /usr/sbin/postfix start

If you'd like sendmail to run every time you start your machine (which I bet you do), you can create and add the following content to /Library/LaunchAgents/sendmail.plist:

<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>sendmail</string>

    <key>OnDemand</key>
    <false/>

    <key>UserName</key>
    <string>root</string>

    <key>GroupName</key>
    <string>root</string>

    <key>ProgramArguments</key>
    <array>
        <string>/usr/sbin/postfix</string>
        <string>start</string>
    </array>
</dict>
</plist>

Then, to start it right now, run the following:

sudo launchctl load /Library/LaunchAgents/sendmail.plist

You'll notice some errors in the output when running the command (see my example session below), but it should work just fine regardless.

Last login: Fri Jan 25 10:15:25 on ttys004
tlhunter@amalthea:~ $ php -a
Interactive shell
php > $result = mail("test@example.com", "PHP Mail Test", "Hi Tom, This is a test");
sendmail: fatal: chdir /Library/Server/Mail/Data/spool: No such file or directory
php > exit
tlhunter@amalthea:~ $ sudo mkdir -p /Library/Server/Mail/Data/spool
Password:
tlhunter@amalthea:~ $ sudo /usr/sbin/postfix set-permissions
chown: /usr/share/man/man1/postalias.1.gz: No such file or directory
tlhunter@amalthea:~ $ sudo /usr/sbin/postfix start
postfix/postfix-script: warning: group or other writable: /Library/Server/Mail/Data/mta
postfix/postfix-script: starting the Postfix mail system
tlhunter@amalthea:~ $ php -a
Interactive shell
php > $result = mail("test@example.com", "PHP Mail Test", "Hi Tom, This is a test");
php >
Tags: #macos #php
Thomas Hunter II Avatar

Thomas has contributed to dozens of enterprise Node.js services and has worked for a company dedicated to securing Node.js. He has spoken at several conferences on Node.js and JavaScript and is an O'Reilly published author.