Send Mail Using msmtp & sendmail With PHP’s mail() Function with Rackspace Hosted Email on a Ubuntu Server

By on

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.
defaults

# Enable or disable TLS/SSL encryption.
auth on
tls on
tls_starttls off
tls_certcheck on
tls_trust_file /etc/ssl/certs/ca-certificates.crt

# Set up a default account's settings.
account default
add_missing_from_header on
logfile ~/.msmtp.log
host "secure.emailsrvr.com"
port 465
domain "<domain.com>"
maildomain "<domain.com>"
user <user@domain.com>
password "<password>"
from "<user@domain.com>"

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 user@domain.com with the email recipients email address for testing.
echo -e "Subject: Testing" | msmtp --debug -t user@domain.com

6. Update PHP’s php.ini settings

  • sendmail_path = “/usr/bin/msmtp -t”

7. Test Using PHP mail()

<?php
// 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@domain.com with the recipient address
$bool = mail('email@domain.com', 'Here Is What I Wanted to Send', $message);

var_dump($bool);

Category: Uncategorized | Comments: Comments Off on Send Mail Using msmtp & sendmail With PHP’s mail() Function with Rackspace Hosted Email on a Ubuntu Server