Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.