This post is a way for me to jog my memory when I need to setup PHP’s mail function to use SMTP. This method requires sendmail, msmtp and a Ubuntu server. Most likely, sendmail is installed by default on Ubuntu. I won’t go into installing sendmail, though it is pretty straightforward. The approach is very similar under other Linux distros too.
Also, in this example the password is not encrytped, though others have recommended this approach. See, “passwordeval”, which can be used to obtain the password from the output of an an executable.
1. Install msmtp
sudo apt-get install msmtp
2. Configure msmtp
- Create a file in your user directory ~/ named .msmtprc
3. Update the contents of .msmtprc
Replace instances of <...> with your pertinent values.
# Set defaults.
# Enable or disable TLS/SSL encryption.
# Set up a default account's settings.
4. Make sure the permissions are set on the .msmtprc file.
chmod 600 .msmtprc
The .msmtprc file should be owned by the user that the web server is running under, www-data for example.
You can also setup a default configuration file at /etc/msmtprc. This file should also be chmod 600, and likely owned by root.
5. Test the msmtp settings
# Replace email@example.com with the email recipients email address for testing.
echo -e "Subject: Testing" | msmtp --debug -t firstname.lastname@example.org
6. Update PHP’s php.ini settings
- sendmail_path = “/usr/bin/msmtp -t”
7. Test Using PHP mail()
// The message
$message = "Line 1\r\nLine 2\r\nLine 3";
// In case any of our lines are larger than 70 characters, we should use wordwrap()
$message = wordwrap($message, 70, "\r\n");
// Send - replace email@example.com with the recipient address
$bool = mail('firstname.lastname@example.org', 'Here Is What I Wanted to Send', $message);