Skip to content

Instantly share code, notes, and snippets.

@Archie22is
Forked from bradyvercher/readme.md
Created January 5, 2017 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Archie22is/b48bfd9d242c8afd0c6f7a9222efea65 to your computer and use it in GitHub Desktop.
Save Archie22is/b48bfd9d242c8afd0c6f7a9222efea65 to your computer and use it in GitHub Desktop.
Configure WordPress to send email through an SMTP server.

WordPress SMTP Configuration

Usage

  1. Install and activate the smtp-config.php file as a plugin or drop it in /mu-plugins.
  2. Define the necessary constants in wp-config.php.

Configuration Examples

MailHog

Route email through MailHog without authentication.

<?php
define( 'CEDARO_SMTP_HOST', 'localhost:1025' );

SparkPost

Send email using SparkPost.

<?php
define( 'CEDARO_SMTP_HOST', 'tls://smtp.sparkpostmail.com:587' );
define( 'CEDARO_SMTP_USERNAME', 'SMTP_Injection' );
define( 'CEDARO_SMTP_PASSWORD', '{password}' );

Bonus

To configure the default From Name and Email, add this snippet in the action callback:

$phpmailer->setFrom(
	apply_filters( 'wp_mail_from',      'from@example.com' ),
	apply_filters( 'wp_mail_from_name', 'Acme Company' )
);
<?php
/**
* Plugin Name: SMTP Configuration
*/
/**
* Configure PHPMailer to use SMTP.
*
* @param PHPMailer $phpmailer PHPMailer instance passed by reference.
*/
add_action( 'phpmailer_init', function( $phpmailer ) {
// Bail if an SMTP host hasn't been defined.
if ( ! defined( 'CEDARO_SMTP_HOST' ) ) {
return;
}
$phpmailer->isSMTP();
$phpmailer->Host = CEDARO_SMTP_HOST;
// Enable SMTP authentication if username and password are defined.
if ( defined( 'CEDARO_SMTP_USERNAME' ) && defined( 'CEDARO_SMTP_PASSWORD' ) ) {
$phpmailer->SMTPAuth = true;
$phpmailer->Username = CEDARO_SMTP_USERNAME;
$phpmailer->Password = CEDARO_SMTP_PASSWORD;
}
} );
<?php
/**
* SMTP host.
*
* Format: {protocol}://{host}:{port}
*
* The protocol and port are optional. Protocol can be 'ssl' or 'tls'.
*/
define( 'CEDARO_SMTP_HOST', 'tls://smtp.example.com:587' );
/**
* SMTP username.
*/
//define( 'CEDARO_SMTP_USERNAME', '' );
/**
* SMTP password.
*/
//define( 'CEDARO_SMTP_PASSWORD', '' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment