Easy SMTP email settings for WordPress

I’ve written a number of posts on the WordPress email settings for using the mail function wp_mail.  Some of this has been information on troubleshooting your WordPress email settings, and one of the solutions to problems with wp_mail that I have addressed in the past has been to use an SMTP server for sending mail rather than relying on the webserver.

For some, this may be something you want to use a plugin for, since WordPress does not have much in the way of email settings in the admin panel.  There are several plugins available for this.  But personally, I prefer to not use plugins when a very simple code snippet will do.

Setting up WordPress to use SMTP for sending email is extremely simple.  You don’t really need any different information than you would for email plugin settings.  All you need is your login credentials, the account information, server location and you can do this all with a few lines of code added to your functions.php file.

Sound good?  Great – let’s get started.

WordPress’s email function wp_mail is essentially a wrapper for phpmailer, a popular email class for PHP.  WordPress has a little known action hook when phpmailer is initialized, phpmailer_init.  This allows you to establish the phpmailer instance as using SMTP.

Here is a code snippet example with comments for each setting to configure WordPress to sent SMTP email:

function send_smtp_email( $phpmailer )
	// Define that we are sending with SMTP

	// The hostname of the mail server
	$phpmailer->Host = "smtp.example.com";

	// Use SMTP authentication (true|false)
	$phpmailer->SMTPAuth = true;

	// SMTP port number - likely to be 25, 465 or 587
	$phpmailer->Port = "587";

	// Username to use for SMTP authentication
	$phpmailer->Username = "yourusername";

	// Password to use for SMTP authentication
	$phpmailer->Password = "yourpassword";

	// The encryption system to use - ssl (deprecated) or tls
	$phpmailer->SMTPSecure = "tls";

	$phpmailer->From = "your-email-address";
	$phpmailer->FromName = "Your Name";

To use this snippet, you will need to adjust the settings according to your email service requirements. Check with your host.

The snippet, once configured, can be added to your theme’s functions.php file.

For more information on testing, troubleshooting, and changing your WordPress email configuration for wp_mail, here are some additional posts: