The humble PHP
mail() function is a handy friend to have. Whether sending yourself debugging messages from a test server, or implementing a quick-and-dirty contact form, I’ve always been able to rely on sending quick email messages from the server.
At least, this is the normal experience on a shared LAMP server. Email gets sent, more or less like magic, and I don’t have to worry too much about the fine details behind the scenes. But now that I’ve upgraded to my own VPS, things can get a little hairy in email-land.
Don’t host your own mail server
Email may be prehistoric technology that predates even the internet, but that doesn’t mean it’s simple to implement. The last thing you want is to manage a full-blown email server. Trust me, leave that to the pros.
Still, you want your PHP scripts to be able to send one-way messages. So you need to hook your server up to an existing SMTP mail service. I’ll be using Postmark to handle that for me. They’re good people — they’ll make sure your emails don’t get marked as spam and all that good stuff.
My VPS is running Ubuntu 16.04 and Apache 2.4. The most common email packages out there are sendmail and postfix. But we’re not going to use either of them, because we don’t need a complete email server that receives messages and has mailboxes and everything. All we want to do is send messages.
Let’s stop those services from running and uninstall them, then:
$ service sendmail stop $ service postfix stop $ apt-get remove sendmail $ apt-get remove postfix
Install and configure Simple SMTP (sSMTP)
Simple SMTP (sSMTP) is a package that does just what it says on the tin. Let’s install it.
$ apt-get install ssmtp
Next, edit the sSMTP configuration file.
$ nano /etc/ssmtp/ssmtp.conf
I needed the following SMTP details to configure my server:
- Hostname (e.g. smtp.postmarkapp.com)
- Port (e.g. 25)
Here’s what my
ssmtp.conf file looks like (I’ve set firstname.lastname@example.org as my sender signature in Postmark):
email@example.com mailhub=smtp.postmarkapp.com:25 AuthUser=MY-POSTMARK-SERVER-API-TOKEN AuthPass=MY-POSTMARK-SERVER-API-TOKEN hostname=samnabi.com
If you see any lines that say
FromLineOverride, you can comment those out.
Next up, let’s edit sSMTP’s list of aliases:
$ nano /etc/ssmtp/revaliases
This file lists which apache users are allowed to send mail through sSMTP. My PHP applications are run under the
www-data user, so I want to enable that user, plus
Good to go!
Go ahead and
reboot that server, your PHP
mail() functions should be working now!
If you need to debug anything, check your Apache logs at
I wrote this blog post because everything else I found on the internet ended up in a dark spiral of cryptic forum posts and listserv archives. If anything’s unclear here, leave a comment! I’ll do my best to clear up any confusing parts of the process.Sam Nabi