Email PHP Intermediate

Send WordPress Email Through SMTP

Send all WordPress email through your email provider's SMTP server, with the login details kept in wp-config.php.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 20 lines
// In wp-config.php:
// define( 'NAHNU_SMTP_HOST', 'smtp.postmarkapp.com' );
// define( 'NAHNU_SMTP_PORT', 587 );
// define( 'NAHNU_SMTP_USER', 'your-smtp-username' );
// define( 'NAHNU_SMTP_PASS', 'your-smtp-password' );

add_action( 'phpmailer_init', function ( PHPMailer\PHPMailer\PHPMailer $mailer ): void {
	if ( ! defined( 'NAHNU_SMTP_HOST' ) || ! defined( 'NAHNU_SMTP_USER' ) || ! defined( 'NAHNU_SMTP_PASS' ) ) {
		return;
	}

	$mailer->isSMTP();
	$mailer->Host       = NAHNU_SMTP_HOST;
	$mailer->Port       = defined( 'NAHNU_SMTP_PORT' ) ? (int) NAHNU_SMTP_PORT : 587;
	$mailer->SMTPAuth   = true;
	$mailer->Username   = NAHNU_SMTP_USER;
	$mailer->Password   = NAHNU_SMTP_PASS;
	$mailer->SMTPSecure = 465 === $mailer->Port ? 'ssl' : 'tls';
	$mailer->Timeout    = 10;
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

Don't use with WP Mail SMTP, FluentSMTP, Post SMTP. Check the notes below before adding it.

By default WordPress sends email with the server’s PHP mail function, which many inboxes treat as suspicious. Sending through a real email service like Postmark, Amazon SES or your own mail provider makes delivery much more reliable.

How it works

WordPress sends every email through PHPMailer, and phpmailer_init lets you configure it just before sending. The snippet switches it to SMTP and sets the server, port and login.

The details come from constants in wp-config.php, so the password isn’t stored in the database or in the snippet. If any constant is missing, the snippet does nothing and WordPress sends as normal.

Port 465 uses SSL, and any other port, usually 587, uses STARTTLS.

Things to watch

  • Set your From address to a domain your email provider has verified, using “Change the WordPress From Name and Email”.
  • Add SPF, DKIM and DMARC records for your domain, as your provider explains.
  • Don’t use this with an SMTP plugin. Pick one.

How to test it

Go to Tools → Site Health and run the test, or use “Lost your password?” on a test account. Check your provider’s activity log for the message.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only