Use Gmail SMTP Servers for Sending Emails from WordPress
MSMTP is very lightweight and has the ability to send emails via an existing SMTP server, like Gmail’s or Yahoo’s.
To get it working, there’s a few tricks. I’ve pieced this together from this post and this post. And when on DigitalOcean, there’s an IPv6 issue that causes major delays in sending the email, which there’s a fix for at the end of this post.
1. Install msmtp
sudo apt-get install msmtp
2. Configure msmtp to use Gmail
/etc/msmtprc as root: sudo nano /etc/msmtprc, and add the following, removing whatever else is there:
# Gmail/Google Apps account gmail host smtp.gmail.com port 587 from firstname.lastname@example.org user email@example.com password enter-password-here! auth on tls on tls_trust_file /etc/ssl/certs/ca-certificates.crt # Default account to use account default : gmail
You’ll want to replace the
user directive with a valid Gmail email address, a Gmail account or a Google Apps email address will work, too. Don’t forget to change
enter-password-here! to the actual password for the Gmail account your using.
3. Remove Sendmail
sudo apt-get remove sendmail-bin
4. Setup Some Aliases
Lots of software on Linux systems uses the sendmail command. Instead, we’re using msmtp, so we’re essentially invoking msmtp when the
sendmail command is run.
sudo ln -s /usr/bin/msmtp /usr/sbin/sendmail sudo ln -s /usr/bin/msmtp /usr/bin/sendmail sudo ln -s /usr/bin/msmtp /usr/lib/sendmail
5. Tell PHP About msmtp
First, locate your
php.ini file that’s being used by Apache. It’s typically in
/etc/php5/apache2/php.ini. If that’s not it, use PHP’s
phpinfo() function to find the location of your
sendmail_path = in
php.ini and replace it with this:
sendmail_path = "/usr/bin/msmtp -t"
Now you should be able to send mail using PHP’s mail() function, which will use the Gmail SMTP server to send emails. Add this to a PHP file and access it through your browser to see if it works:
<?php if(mail("firstname.lastname@example.org","A Subject Here","Hi there,nThis email was sent using PHP's mail function.")) print "Email successfully sent"; else print "An error occured"; ?>
6. Disable IPv6 If You Experience Slowness
/etc/gai.conf like so:
sudo nano /etc/gai.conf
Now, look for a line that looks like this:
#precedence ::ffff:0:0/96 100. Uncomment that line (remove the #) and save
/etc/gai.conf. An explanation of why this helps can be found in this comment at the DigitalOcean article.
That should be it. If you run into any issues please do leave a comment, I’ll do my best to help you out. I may have missed a part, so no guarantees this will work for you. It does however work wonderfully on a DigitalOcean droplet that’s running Ubuntu 14.04 with a pretty standard LAMP stack.
You should now be able to send email from WordPress on DigitalOcean.