Set Up WordPress SMTP Without a Plugin, Even on a Multisite Network

Date:

WordPress mail goes out as wordpress@ your domain, from the web server, and lands in spam. An SMTP plugin fixes that. So do about twenty lines of code, and on a network of sites the code can give every site its own mailbox and its own password.

The short answer: To set up WordPress SMTP without a plugin, use one function on the phpmailer_init hook switches WordPress from PHP’s mail() to your mailbox’s SMTP server with a real login. A wp_mail_from filter replaces the wordpress@ address, and the password stays in wp-config.php as a constant. On a multisite network, list each site’s domain with its own mailbox and its own named constant, so every site sends as itself. Run the code everywhere, not just on the front end, then check a real message’s headers for SPF, DKIM and DMARC passing.

Why WordPress mail needs SMTP at all

Everything WordPress sends goes through wp_mail(): contact forms, password resets, new-user notices, plugin alerts. By default it hands the message to PHP’s mail(), so it leaves from the web server, or from a relay your host puts behind it, with wordpress@ your domain as the sender. Your domain’s SPF record doesn’t list that server and nothing signs the message with your domain’s DKIM key, so it fails DMARC and lands in spam. Reading the verdicts in a message’s headers, step by step, is covered in Contact Form 7 emails going to spam, which fixes it with a plugin.

Just before sending, wp_mail() fires phpmailer_init and hands over the mail object. Anything you change there applies to every message WordPress sends. That’s the whole trick.

Set up WordPress SMTP without a plugin

For a single site, with example values. It changes the transport to SMTP, logs in as your mailbox, and swaps the default address:

// Send all WordPress mail through your mailbox's SMTP server.
// The password lives in wp-config.php, never here (see below).
add_action( 'phpmailer_init', function ( $phpmailer ) {
    if ( ! defined( 'SITE_SMTP_PASS' ) || '' === SITE_SMTP_PASS ) {
        return; // not configured: WordPress keeps its default transport
    }
    $phpmailer->isSMTP();
    $phpmailer->Host       = 'smtp.example.com';
    $phpmailer->Port       = 465;
    $phpmailer->SMTPSecure = 'ssl';               // TLS from the start on 465; use 'tls' with port 587
    $phpmailer->SMTPAuth   = true;
    $phpmailer->Username   = 'hello@example.com';
    $phpmailer->Password   = SITE_SMTP_PASS;
    $phpmailer->Sender     = 'hello@example.com'; // envelope sender: the mailbox you logged in as
} );

// Replace the default wordpress@ address, wherever it was set.
add_filter( 'wp_mail_from', function ( $from ) {
    return ( 0 === strpos( $from, 'wordpress@' ) ) ? 'hello@example.com' : $from;
} );
add_filter( 'wp_mail_from_name', function ( $name ) {
    return ( 'WordPress' === $name ) ? 'Example Site' : $name;
} );
Code language: PHP (php)

What each part is for:

  • The guard at the top. Until the password constant exists, the function returns early and mail goes out the old way. You can add the code first and the password second without breaking anything in between.
  • Host, port and encryption come from your mail provider’s settings page. Port 465 with ssl encrypts the connection from the first byte; port 587 with tls starts plain and upgrades. Use whichever your provider documents.
  • Sender is the envelope address, the one receiving servers check SPF against. With SMTP, PHPMailer (the mail library inside WordPress) falls back to the From address when it’s empty, so most of the time this line changes nothing. It matters when a plugin sets a From of its own: the envelope still names the mailbox that logged in.
  • The wp_mail_from filter runs on every message, including ones whose From came from a form’s own settings, so it catches a contact form’s wordpress@ sender too. It only rewrites wordpress@ addresses and leaves any other deliberate From alone.

Keep the password in wp-config.php

The mailbox password goes in wp-config.php, above the line that says to stop editing:

define( 'SITE_SMTP_PASS', 'the mailbox password' );Code language: PHP (php)

Not in the code itself. A snippet plugin saves its code in the database, in plain text, where every administrator can read it and every database export carries a copy. wp-config.php sits outside the database, and the code reads it only at the moment of sending.

Run it everywhere, not just on the front end

Snippet plugins let you choose where code runs, and “front end only” looks tempting for something visitors trigger. It would miss most of your mail. WordPress sends from admin screens (new users, password resets), from scheduled tasks (the automatic-update report comes from WP-Cron) and from REST requests: Contact Form 7 submits its forms to a REST route, not to the page. Set it to run everywhere.

Give each site on a network its own mailbox

On a multisite network, WordPress builds the default sender from the network’s main domain, not the site’s own. So a site you never set up still sends mail, as wordpress@ the main domain, from the web server, and that mail fails the same checks. Code that runs on the main site only fixes the main site only.

A site you never set up still sends mail, just as wordpress@ the network’s main domain.

Each site needs a mailbox on its own domain, because a mailbox can only vouch for mail from its own domain. One copy of the code, active on every site, can pick the right one:

// One copy for the whole network: each site sends from its own domain's mailbox.
// Each password is its own constant in wp-config.php.
function example_site_mailbox() {
    $mailboxes = array(
        'example.com' => array( 'host' => 'smtp.example.com', 'user' => 'hello@example.com', 'pass' => 'EXAMPLE_COM_SMTP_PASS' ),
        'example.org' => array( 'host' => 'smtp.example.org', 'user' => 'hello@example.org', 'pass' => 'EXAMPLE_ORG_SMTP_PASS' ),
    );
    $domain = preg_replace( '/^www\./', '', (string) wp_parse_url( home_url(), PHP_URL_HOST ) );
    $box    = isset( $mailboxes[ $domain ] ) ? $mailboxes[ $domain ] : null;
    return ( $box && defined( $box['pass'] ) && '' !== constant( $box['pass'] ) ) ? $box : null;
}

add_action( 'phpmailer_init', function ( $phpmailer ) {
    $box = example_site_mailbox();
    if ( ! $box ) {
        return; // this site has no mailbox set up yet: WordPress keeps its default
    }
    $phpmailer->isSMTP();
    $phpmailer->Host       = $box['host'];
    $phpmailer->Port       = 465;
    $phpmailer->SMTPSecure = 'ssl';
    $phpmailer->SMTPAuth   = true;
    $phpmailer->Username   = $box['user'];
    $phpmailer->Password   = constant( $box['pass'] );
    $phpmailer->Sender     = $box['user'];
} );

add_filter( 'wp_mail_from', function ( $from ) {
    $box = example_site_mailbox();
    return ( $box && 0 === strpos( $from, 'wordpress@' ) ) ? $box['user'] : $from;
} );
Code language: PHP (php)

And in wp-config.php, one line per site:

define( 'EXAMPLE_COM_SMTP_PASS', 'the example.com mailbox password' );
define( 'EXAMPLE_ORG_SMTP_PASS', 'the example.org mailbox password' );Code language: PHP (php)

On a test site, firing phpmailer_init without sending anything showed the three cases you’d expect. A listed site with its constant got SMTP, its own host, login and envelope sender, and its wordpress@ sender rewritten. A listed site whose constant wasn’t added yet, and a site not in the list, were left on WordPress’s default, untouched.

One wp-config.php can hold a password for every site, as long as each has its own name.

That naming is something a plugin with fixed constant names can’t offer. FluentSMTP, for one, can read its login from wp-config.php, but only from two fixed names, FLUENTMAIL_SMTP_USERNAME and FLUENTMAIL_SMTP_PASSWORD, and a network has one wp-config.php. Two sites with different mailboxes can’t both use that mode. With your own code you name each constant yourself.

Where to put it so it runs on every site: a must-use plugin (a PHP file in wp-content/mu-plugins, which WordPress loads on every site of the network) or a snippet plugin’s network-wide snippet. Two things to know before choosing this over a plugin:

  • Only someone who can edit wp-config.php can set or change a password, usually the network owner. A site’s own administrator can’t. If each site’s admin should manage their own mailbox from the dashboard, a plugin that stores the login per site suits that better.
  • If the network’s sites are folders of one domain (example.com/shop/), they share that domain, so one mailbox can serve them all. Key the list by get_current_blog_id() instead of the domain if they need different ones.

When a send fails

If test sends don’t arrive and nothing on screen says why, hook the action WordPress fires when a send fails, briefly:

add_action( 'wp_mail_failed', function ( $error ) {
    error_log( 'wp_mail failed: ' . $error->get_error_message() );
} );
Code language: PHP (php)

On a test site whose mail server refused the login, one send with the code above gave:

wp_mail failed: SMTP Error: Could not authenticate.
wp_mail returned falseCode language: JavaScript (javascript)

With the login accepted, the same send returned true and logged nothing. That message is the most common one: the constant doesn’t hold the mailbox’s current password. The plugin article’s step on that error walks through the fix, and it’s the same with code. Remove the hook afterwards: a log of failures that may include addresses shouldn’t outlive the problem.

To produce both results on demand before touching the real mailbox, point the hook at a local server that refuses or accepts the login: how to test WordPress SMTP without sending a real email.

Worth knowing: wp_mail() returning true only means the mail server took the message. It says nothing about which folder it lands in, the same gap as trusting a success message instead of checking the result.

Prove it with a real message

Send something real, such as a contact-form message or a password reset, to an outside mailbox, open it, and read the receiving server’s verdicts (in Gmail, Show original). From the test site, summarised with the domain written as example.com:

From:   hello@example.com
SPF:    pass, for hello@example.com
DKIM:   pass, signed for example.com
DMARC:  passCode language: CSS (css)

The DKIM signature comes for free: a mail provider signs mail sent through its own servers with the domain’s key, which it can’t do while WordPress goes around it. On a network, send one test from every site you listed. Only once they all pass is it safe to make the domain’s DMARC policy stricter, as the plugin article’s last step explains.

Plugin or code?

An SMTP plugin such as WP Mail SMTP or FluentSMTP does the same job through a settings screen, and adds things this code doesn’t have: a test-email button, a log of sent mail, and connectors for sending services that use an API instead of SMTP. Pick one if you want those, if each site’s admin should manage their own mailbox, or if nobody will maintain code.

The code is the leaner choice when the mailbox offers plain SMTP and you’d rather have a few lines you can read in one sitting, and on a network it’s the way to keep every site’s password out of the database under a name of its own. The wider trade-off is in code snippet or plugin.

Moving WordPress mail to SMTP, in orderProve the problem, switch the transport, prove the fix, and only then tighten DMARC.
Read the headers

Show original on a real message: do SPF, DKIM and DMARC pass for your domain?

Password

A constant in wp-config.php, not in the database. On a network, one per site.

The snippet

phpmailer_init: SMTP and the login. wp_mail_from: drop wordpress@. Run everywhere.

Send a test

Nothing arrives? Log wp_mail_failed. Could not authenticate = wrong password.

fails first most often
Prove, then tighten

SPF, DKIM, DMARC all pass? Only now move DMARC from p=none to quarantine.

WordPress's default sends as wordpress@ your domain from the web server, which your SPF record doesn't list and which can't sign with your DKIM key.

The short version

  • One phpmailer_init function switches WordPress mail to your mailbox’s SMTP server with a real login; a wp_mail_from filter replaces the wordpress@ address.
  • The password goes in wp-config.php, not in code saved to the database.
  • Run it everywhere, because WordPress sends from admin screens, cron and REST requests, not only the front end.
  • On a network, list every site with a mailbox on its own domain and a constant with its own name. A site left out sends as wordpress@ the main domain.
  • Check a real message’s headers from each site before making DMARC stricter.

Frequently Asked Questions

Should I use port 465 or 587 for WordPress SMTP?

Whichever your mail provider documents. Port 465 uses TLS from the start (SMTPSecure = 'ssl' in PHPMailer); port 587 connects plainly and then upgrades with STARTTLS (SMTPSecure = 'tls'). Both encrypt the login and the message.

Does wp_mail returning true mean the email was delivered?

No. It means the mail server accepted the message for delivery. Whether it reaches the inbox, the spam folder or nowhere is decided later by the receiving side, which is why you check a real message’s headers.

Can I use this code with a sending service instead of my mailbox?

Yes, if the service offers an SMTP login: put its server, port, username and password in the same places. A service you can only reach through its own web API needs a plugin or its own library, because this code only speaks SMTP.

Share post:

Subscribe

Popular

More like this
Related

WooCommerce Search by SKU or ISBN Finds Nothing? It Never Looks There

A shopper types the SKU from your catalog, or the ISBN printed on the back of a book, and gets "No products were found". The product is right there, and the number is on its page. Search simply never reads that part of the product.

Computer Slow but CPU and Memory Look Normal? Check the Handle Count

Chrome takes a minute to open, or doesn't open at all. Every click waits. You open Task Manager expecting to find the culprit, and it tells you everything is fine. Here is the number that isn't, and the fix that takes two minutes.

Kernel-Power 41 Tells You Your PC Restarted, Not Why

Your PC restarts with no blue screen, and the only clue is a critical event saying it didn't shut down cleanly. Here is how to get from that event to a short list of suspects.

Stop WordPress Content Scraping Through Feeds, the REST API and Load More

Someone copies your whole archive and never crawls a single page. A default WordPress site hands every post's full text to any visitor who asks the right three addresses.