WordPress already ships a mail function, so you do not need an SMTP plugin to send reliable email. The function is wp_mail(), and the piece most people are actually missing is not a plugin but a properly authenticated sending path: SMTP credentials wired in through the phpmailer_init action, plus SPF and DKIM records on your domain. You can do all of that in about forty lines of code that live in a must use file.
wp_mail( $to, $subject, $message, $headers, $attachments ) for any email your site sends. To route it through a real SMTP service instead of the server’s local sendmail, drop a file into wp-content/mu-plugins/ that hooks phpmailer_init, calls $phpmailer->isSMTP(), and reads the host, port, username, and password from constants defined in wp-config.php. Then publish SPF and DKIM records for the sending domain, or the mail will still land in spam.Everything here works on the current WordPress 7.1 line and on anything back to WordPress 5.5. No plugin is installed at any point. If you want to understand the file structure a must use file lives in, our beginner tutorial on creating a WordPress plugin covers the plugin directories and headers that the same rules apply to.
Why the PHP mail function fails and wp_mail exists
PHP’s native mail() hands a message to whatever local mail transfer agent the server has, usually sendmail or Postfix. That message leaves from your web server’s IP address, with an envelope sender that frequently does not match the From header, and with no cryptographic signature. Receiving providers treat that combination as unauthenticated bulk mail. Shared hosts make it worse by sharing an IP reputation across hundreds of accounts.
wp_mail() is a wrapper around PHPMailer, the library bundled with WordPress core. By default it still uses the local transport, so simply calling it changes nothing about deliverability. What it gives you is a set of hooks where you can replace the transport, and consistent handling of headers, attachments, and character sets that hand rolled mail() calls always get wrong.
wp_mail basics: arguments, headers, attachments
The signature is five arguments, and only the first three are required. Recipients can be a string or an array. Headers can be a string, an array of strings, or an associative array.
$to = 'ops@example.com';
$subject = 'Nightly backup finished';
$body = "The backup completed at " . current_time( 'mysql' ) . ".\n";
$headers = array(
'From: Site Robot <robot@example.com>',
'Reply-To: support@example.com',
'Cc: audit@example.com',
);
$attachments = array( WP_CONTENT_DIR . '/uploads/reports/nightly.csv' );
$sent = wp_mail( $to, $subject, $body, $headers, $attachments );
if ( ! $sent ) {
error_log( 'wp_mail returned false for ' . $to );
}A false return means PHPMailer threw an exception before handing the message off. A true return means the message was accepted by the transport, which is not the same as delivered. That distinction is the source of most “WordPress says it sent but nothing arrived” tickets.
Sending HTML mail properly
By default WordPress sends plain text. Switching to HTML globally with the wp_mail_content_type filter is the classic mistake, because it then applies to every email WordPress sends, including password resets that contain raw URLs. Scope the filter to the one call and remove it afterwards.
function gb_send_html_mail( $to, $subject, $html ) {
$set_html = static function () { return 'text/html'; };
add_filter( 'wp_mail_content_type', $set_html );
$result = wp_mail( $to, $subject, $html );
remove_filter( 'wp_mail_content_type', $set_html );
return $result;
}An alternative that avoids the global filter entirely is to build a multipart message inside phpmailer_init, setting $phpmailer->AltBody to a plain text version. Multipart mail scores better with filters than an HTML only message, and it is the shape every reputable sender uses.
Wiring SMTP through phpmailer_init
The phpmailer_init action passes the PHPMailer object by reference just before the message is sent, which is exactly where you swap the transport. Put this in wp-content/mu-plugins/gb-smtp.php. Files in that directory load automatically, cannot be deactivated from the admin, and are not listed as plugins, which is precisely what you want for infrastructure.
<?php
/**
* Plugin Name: GB SMTP Transport
* Description: Routes wp_mail through an authenticated SMTP relay.
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
add_action( 'phpmailer_init', 'gb_configure_smtp' );
function gb_configure_smtp( $phpmailer ) {
if ( ! defined( 'GB_SMTP_HOST' ) ) {
return;
}
$phpmailer->isSMTP();
$phpmailer->Host = GB_SMTP_HOST;
$phpmailer->Port = (int) GB_SMTP_PORT;
$phpmailer->SMTPAuth = true;
$phpmailer->Username = GB_SMTP_USER;
$phpmailer->Password = GB_SMTP_PASS;
$phpmailer->SMTPSecure = GB_SMTP_PORT === 465 ? 'ssl' : 'tls';
$phpmailer->SMTPAutoTLS = true;
$phpmailer->CharSet = 'UTF-8';
$phpmailer->setFrom( GB_SMTP_FROM, GB_SMTP_FROM_NAME, false );
$phpmailer->Sender = GB_SMTP_FROM;
}
add_filter( 'wp_mail_from', static fn( $email ) => defined( 'GB_SMTP_FROM' ) ? GB_SMTP_FROM : $email );
add_filter( 'wp_mail_from_name', static fn( $name ) => defined( 'GB_SMTP_FROM_NAME' ) ? GB_SMTP_FROM_NAME : $name );The Sender property sets the envelope sender, which is what SPF is checked against. Setting the From header without setting the envelope sender is one of the most common reasons a correctly published SPF record still produces a soft fail.
Keeping credentials out of the database
Define the constants in wp-config.php, above the line that requires wp-settings.php. Credentials in the options table end up in every database export, every staging clone, and every backup you email to yourself.
define( 'GB_SMTP_HOST', 'smtp.example-relay.com' );
define( 'GB_SMTP_PORT', 587 );
define( 'GB_SMTP_USER', 'apikey' );
define( 'GB_SMTP_PASS', getenv( 'GB_SMTP_PASS' ) ?: '' );
define( 'GB_SMTP_FROM', 'no-reply@example.com' );
define( 'GB_SMTP_FROM_NAME', 'Example Site' );wp-config.php with a live password to version control. Read the secret from an environment variable as shown, or from a file outside the web root, and make sure your backup routine handles it deliberately. Our guide to backing up a WordPress website manually explains which files matter.SPF, DKIM, and DMARC
Authentication happens in DNS, not in PHP. Three records do the work, and the relay you send through will give you the exact values for the first two. Publish them on the domain in your From address.
| Record | Type and host | What it proves | Shape of the value |
|---|---|---|---|
| SPF | TXT on the root domain | This server is allowed to send for the domain | v=spf1 include:relay.example.com ~all |
| DKIM | TXT on selector._domainkey | The message was not altered and came from a key holder | v=DKIM1; k=rsa; p=MIIBIjAN... |
| DMARC | TXT on _dmarc | What receivers should do when SPF and DKIM fail | v=DMARC1; p=none; rua=mailto:dmarc@example.com |
Start DMARC at p=none with a reporting address, read the aggregate reports for a couple of weeks, and only then move to quarantine and reject. Publishing a strict policy before you know every system that sends as your domain is how internal invoices stop arriving. The SPF syntax is defined in RFC 7208 if you need the authoritative rules on include limits.
Testing and logging what actually happened
Two hooks tell you the outcome without guessing. wp_mail_failed receives a WP_Error containing the PHPMailer exception, and wp_mail_succeeded receives the message data after a successful handoff.
add_action( 'wp_mail_failed', static function ( $error ) {
error_log( '[mail] FAILED: ' . $error->get_error_message() );
} );
add_action( 'wp_mail_succeeded', static function ( $data ) {
error_log( '[mail] sent to ' . implode( ',', (array) $data['to'] ) . ' subject: ' . $data['subject'] );
} );
// Verbose SMTP conversation, staging only.
add_action( 'phpmailer_init', static function ( $phpmailer ) {
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
$phpmailer->SMTPDebug = 2;
$phpmailer->Debugoutput = static fn( $str ) => error_log( '[smtp] ' . rtrim( $str ) );
}
}, 20 );Send a test from WP-CLI so you are not depending on a form: wp eval 'var_dump( wp_mail( "you@example.com", "test", "hello" ) );'. Then check the received message’s raw headers for spf=pass and dkim=pass. If either says none or fail, the DNS side is not finished.
Troubleshooting
wp_mail returns true but nothing arrives. The message was accepted by the local transport and then dropped or filtered downstream. Check the mail log on the server (/var/log/mail.log on most Linux hosts), and confirm you are actually on SMTP by adding a temporary error_log( $phpmailer->Mailer ); inside your phpmailer_init callback.
SMTP connect() failed. Outbound port 587 or 465 is blocked, which many shared hosts do by default. Test with nc -vz smtp.example-relay.com 587 from SSH. If it is blocked, ask the host to open it or use the relay’s HTTP API instead of SMTP.
Mail lands in spam despite passing SPF. Alignment is failing: SPF passes for the envelope sender but that domain does not match the From header domain. Set $phpmailer->Sender to an address on the same domain as your From header, as shown above.
Password reset emails have broken HTML. Something set wp_mail_content_type to text/html globally. Search the theme and any must use files for that filter and scope it to individual sends.
Everything worked until the site was cloned to staging. Staging is now sending real email to real customers. Add a guard in the must use file that short circuits pre_wp_mail and returns true whenever the site URL is not production.
Frequently asked questions
Is an SMTP plugin ever the better choice?
For a site handed to a nontechnical owner, yes, because the settings screen and logging UI matter more than code cleanliness. If you control deployment and want credentials in configuration rather than the database, the must use file shown here is fewer moving parts and one less thing to keep updated.
Can I send through Gmail or a personal mailbox?
Technically yes, using an app password and smtp.gmail.com on port 587, but consumer mailboxes carry low sending limits and terminate accounts used for transactional volume. For anything beyond a contact form on a personal site, use a transactional relay built for the job.
How do I stop WordPress sending from wordpress@yourdomain?
Filter wp_mail_from and wp_mail_from_name, as in the code above. Both run inside wp_mail() before the message is built. Keep the address on a domain you control and can publish DNS records for, otherwise you have traded a cosmetic problem for a deliverability one.
Does this work with the block editor’s form blocks or WooCommerce?
Yes. Almost every plugin sends through wp_mail() rather than PHP’s mail(), so replacing the transport at phpmailer_init changes all of them at once. The rare exception is a plugin that calls PHPMailer directly, which you can spot by grepping for new PHPMailer.
What is the difference between wp_mail_failed and a bounce?
wp_mail_failed fires when the handoff to the transport fails, so a bad password or a refused connection. A bounce happens later, at the receiving server, and never reaches your PHP process. To see bounces you need the webhook or log feed your relay provides.
The bottom line
Sending mail from WordPress without a plugin is not a workaround; it is the same code an SMTP plugin runs, minus the settings screen. One must use file, five constants in wp-config.php, and three DNS records covers everything a normal site needs.
Do the DNS work first, because no amount of PHP fixes an unauthenticated domain. Then add the transport, turn on the failure logging, and send a real test to an address at a large provider so you can read the authentication results in the raw headers. The official wp_mail reference lists every filter available if you need to go further.
About this article: GeekBlog covers U.S. technology news, AI, phones, smartwatches and gaming. Every story is written and checked under our Editorial Policy. Spotted a mistake or have a story tip? Contact our editors.

