Easy SMTP email settings for WordPress

wp-mail-function

If you are facing problems with wp_mail function in sending emails, the solution is to use an SMTP server rather than relying on the webserver.

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:

/**
 * This function will connect wp_mail to your authenticated
 * SMTP server. This improves reliability of wp_mail, and 
 * avoids many potential problems.
 */
 
add_action( 'phpmailer_init', 'send_smtp_email' );

function send_smtp_email( $phpmailer ) {

	// Define that we are sending with SMTP
	$phpmailer->isSMTP();

	// 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";

	// Encryption system to use - ssl or tls
	$phpmailer->SMTPSecure = "tls";

	$phpmailer->From = "you@yourdomail.com";
	$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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s