Skip to content

feat(providers): support HTTP API providers - #41

Merged
davidperezgar merged 6 commits into
WordPress:trunkfrom
faisalahammad:feature/1-http-api-providers
Nov 22, 2026
Merged

davidperezgar merged 6 commits into
WordPress:trunkfrom
faisalahammad:feature/1-http-api-providers

Conversation

@faisalahammad

@faisalahammad faisalahammad commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Providers can now send through an HTTP API instead of SMTP, with a new send callback. wp_mail() still builds the email as usual (headers, recipients, attachments, From and phpmailer_init), and only the delivery goes to the provider. Errors become a normal wp_mail_failed, so the email log, alerts and test email work with API providers too. Only the contract ships here, no built-in API provider.

Fixes #1

Changes

Provider_Registry

Before:

if ( empty( $provider['configure'] ) || ! is_callable( $provider['configure'] ) ) {
	continue;
}

After:

$provider['configure'] = $provider['configure'] ?? null;
$provider['send']      = $provider['send'] ?? null;
if ( ( null !== $provider['configure'] && ! is_callable( $provider['configure'] ) )
	|| ( null !== $provider['send'] && ! is_callable( $provider['send'] ) )
	|| ( null === $provider['configure'] && null === $provider['send'] ) ) {
	continue;
}

Why: A provider needs configure, send or both. A send-only provider was dropped before.

Transport_PHPMailer (new)

A PHPMailer subclass. When a transport is set, send() runs preSend() (address checks and MIME build), then calls the provider:

try {
	$result = call_user_func( $transport, $this, $values );
} catch ( \Throwable $e ) {
	$result = new \WP_Error( 'smtp_transport', $e->getMessage() );
}

Anything but true becomes a PHPMailer\Exception, with values of password fields replaced by [redacted].

Why: wp_mail() only catches PHPMailer exceptions, so this keeps the core success and failure actions. pre_wp_mail was not used because it skips header parsing and those actions.

Mailer

use_transport() runs on the wp_mail filter. When the active provider has send and is configured, it puts a Transport_PHPMailer in the global $phpmailer, with the same is_email() validator and translations core sets. It does this only when the global is empty or the default PHPMailer / WP_PHPMailer, so a plugin that replaced PHPMailer is left alone and the email is logged as other.

Docs

readme.md has a new "HTTP API providers" section with an example. readme.txt (FAQ and changelog) and AGENTS.md are updated.

Testing

Test provider used (mu-plugin):

add_filter( 'smtp_providers', function ( $providers ) {
	$providers['test-api'] = array(
		'label'    => 'Test API',
		'required' => array( 'api_key' ),
		'fields'   => array( 'api_key' => array( 'label' => 'API key', 'type' => 'password' ) ),
		'send'     => function ( $phpmailer, $values ) {
			if ( 'fail' === $values['api_key'] ) {
				return new WP_Error( 'test_api', 'Rejected: invalid key ' . $values['api_key'] );
			}
			return true;
		},
	);
	return $providers;
} );

Test 1: Provider shows up

  1. Add the mu-plugin above and go to Tools > SMTP > Settings.
  2. Select Test API and save.

Result: the API key field shows instead of the SMTP fields. Before this change, Test API was ignored and the page fell back to Generic SMTP.

Test 2: Success

  1. Set the API key to abc and send a test email.

Result: "Test email sent", and the log shows the email as Sent with provider Test API.

Test 3: Failure

  1. Set the API key to fail and send a test email.

Result: "Rejected: invalid key [redacted]" in the Test tab and in the log. The key is not shown.

Test 4: Generic SMTP

  1. Switch back to Generic SMTP and send a test email.

Result: works as before, with the connection log.

Automated: 399 PHPUnit tests pass, including end-to-end wp_mail() tests for success, failure, Cc, Reply-To and attachments. composer lint is clean.

Screenshots

Before After
Before: Test API is ignored, Generic SMTP is shown After: Test API selected with its API key field

Test email sent through the API provider

Test email sent

Failure, with the key redacted

Test email failed with redacted key

Email log

Email log with sent and failed entries for Test API

Open WordPress Playground Preview

- Add Transport_PHPMailer, a PHPMailer that hands the built email to a
  provider send callback instead of sending it over SMTP
- Swap it in on the wp_mail filter when the configured provider has send
  and wp_mail() would use the default PHPMailer
- Turn a WP_Error or a thrown error from send into a PHPMailer exception,
  with password field values redacted, so wp_mail_failed, the log and the
  alerts keep working
- Accept providers with configure, send or both in Provider_Registry
- Document the send contract in readme.md, readme.txt and AGENTS.md
- Add tests for the transport, the swap and the registry validation

Many mail services offer an HTTP API that works where SMTP ports are
blocked. This lets a provider use it while wp_mail() still parses the
headers, recipients and attachments.

Fixes WordPress#1
@github-actions

Copy link
Copy Markdown

The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs.

If you're merging code through a pull request on GitHub, copy and paste the following into the bottom of the merge commit message.

Co-authored-by: faisalahammad <faisalahammad@git.wordpress.org>
Co-authored-by: davidperezgar <davidperez@git.wordpress.org>

To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook.


Props Bot commands

You can trigger Props Bot actions by commenting on this PR:

  • @propsbot add <username> to give props to a GitHub or WordPress.org user. Requires write access.
  • @propsbot remove <username> to leave a user out of the props. Requires write access.
  • @propsbot refresh to refresh this list. Adding the props-bot label works too.

PHPMailer in WordPress 6.3 keys Reply-To addresses by address, so the
assertion failed on the PHP 7.4 / WP 6.3 job.
@davidperezgar

Copy link
Copy Markdown
Member

Thanks @faisalahammad, this is a well-thought-out foundation. Letting wp_mail() build the email and only delegating delivery keeps headers, attachments and phpmailer_init working, and turning errors into wp_mail_failed means the log, alerts and test email work unchanged. I like that it leaves another plugin's PHPMailer alone, and the end-to-end tests are thorough.

To resolve

  1. Interaction with Support multiple SMTP connections with per-email selection #32 (multiple connections). use_transport() hooks wp_mail at PHP_INT_MAX, the same priority Support multiple SMTP connections with per-email selection #32 uses for select_connection(). The result then depends on registration order. Since use_transport() reads the active provider from the settings, it must run after the connection for that email is chosen. Otherwise the PHPMailer class could not match the provider selected for the email. Please make the order explicit and add a test that combines both.

  2. Secret redaction in errors. str_replace( $secrets, '[redacted]', $message ) only matches the exact value. If an API echoes the key base64- or URL/JSON-encoded, it would still appear in the message and the log. Also, secrets are not sorted longest first (as Redact every password field from the connection log #37 does), so a secret that contains another is only partly redacted.

Smaller suggestions

  • send callbacks that call wp_mail() re-enter on the same global $phpmailer and would corrupt the email in progress. A re-entrancy guard would be safer than documentation alone.
  • configure() still creates the SMTP instance (getSMTPInstance()->Timelimit) for API-only providers.
  • API providers produce no SMTP connection log, so Error_Hints has nothing to analyze. It would help to define what the Test tab shows for them. I have not verified how the current UI behaves.
  • With no built-in API provider, the contract has no real consumer yet. A small reference provider, or a tested example, would help future authors.
  • Let providers declare sending rate limits #31 also edits Provider_Registry, so expect a textual conflict.

Overall this looks good to me once points 1 and 2 are covered.

Disclosure: I used Claude (Claude Code) to help review this PR. I read through its findings and am posting them as my own review.

- Put the transport mailer in place when any provider has a send
  callback, so the provider is read on phpmailer_init. Other wp_mail
  callbacks, like a connection selector, can no longer change the
  result by running first or last.
- Redact base64, URL, JSON and Basic auth forms of secrets, longest
  first.
- Fail an email sent from inside a send callback, without changing
  the email in progress.
- Do not create the SMTP instance for API providers.

Addresses PR feedback.

Refs WordPress#41
@faisalahammad

Copy link
Copy Markdown
Contributor Author

Thanks @davidperezgar for the careful review. I pushed 18f0800 (and merged trunk first in 48dede4).

1. Order with #32

use_transport() no longer reads the active provider. It puts Transport_PHPMailer in place when any registered provider has a send callback. Without a callback set, it sends like PHPMailer. configure() picks the provider on phpmailer_init, after every wp_mail callback ran, so the order of use_transport() and select_connection() does not matter anymore. When #32 lands, configure() only needs to use get_settings(), like the other methods there.

Because of this, use_transport() does not check is_configured() anymore: a connection selector may pick a configured connection while the saved one is not. I changed test_use_transport_does_nothing_until_the_provider_is_configured into test_an_unconfigured_provider_sends_like_phpmailer, which checks that no callback is set and PHPMailer still uses mail. Happy to talk about it if you prefer the old check.

#32 is not merged, so I can not test both together yet. test_the_provider_is_read_when_phpmailer_is_set_up and test_the_provider_is_read_when_an_unconfigured_default_changes add a wp_mail filter at PHP_INT_MAX after the plugin that switches the provider, like select_connection() does, and check the email goes through the picked provider.

2. Redaction

Errors now redact the plain, base64, URL (raw and form) and JSON forms (with and without escaped slashes and unicode) of every password field. They also redact Basic auth tokens (base64( user:secret ), also with an empty user). All values are sorted longest first, like #37. The tests compare the full message.

Smaller suggestions

  • Re-entrancy: added a guard. When a send callback calls wp_mail(), that email gets a new PHPMailer instance and fails with "An email can not be sent while the provider is sending another one." The email in progress is not changed. Tested in test_a_send_callback_can_not_send_another_email and test_phpmailer_can_not_send_while_a_callback_sends.
  • configure() no longer touches getSMTPInstance()->Timelimit for providers with send (test_configure_leaves_the_smtp_time_limit_alone_for_api_providers).
  • Test tab: API providers have no connection log. The tab shows the error message only, without the hint and without the "Connection log" section. I left it like this for now.
  • Reference provider: Support transport-level (HTTP API) providers #1 asks for the contract only, so I kept it out. The readme example and the end-to-end tests use a test provider. I can add one in a follow-up if you want.
  • Let providers declare sending rate limits #31: noted, I will fix the conflict in whichever PR lands second.

412 tests pass and composer lint is clean.

@alexander-sakal alexander-sakal mentioned this pull request Nov 18, 2026
4 of 5 tasks
davidperezgar and others added 2 commits November 21, 2026 13:36
Conflicts resolved:
- Mailer: keep the connection hooks and settings of WordPress#32 and add use_transport() next to them.
  The secrets redacted from the errors of the provider are found with the fields of the connection
  the email goes through, not the default one (new test, which fails without it).
- Provider_Registry, AGENTS.md, readme.txt: keep both the send and the rate_limits changes, and
  put the changelog entry in the 1.3.0 section.

PHPStan, which trunk now runs, flagged this branch. Fixed:
- Delivery_Tracker::remember() documents the null that Mailer passes when another plugin sends.
- Transport_PHPMailer filters the redacted values with a closure, since substr() can return false
  on PHP 7.
- Mailer uses WPINC five times, listed in the baseline like the other uses.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
… it is static

WordPress 6.8 declares setLanguage() as an instance method and stores
the strings per instance, so the static call threw an Error and broke
every send through a transport. Since 6.9 the method and the strings
are static. On 6.8 the transport now keeps the English PHPMailer
errors.
@davidperezgar
davidperezgar merged commit a453050 into WordPress:trunk Nov 22, 2026
40 checks passed
This was referenced Nov 23, 2026
davidperezgar added a commit that referenced this pull request Nov 25, 2026
* Add a Google (Gmail API) provider

Sends through the Gmail API with OAuth 2.0, using the HTTP API provider
support from #41. The site stores a client ID, client secret and refresh
token (gmail.send scope); access tokens are cached per account in a
transient and dropped on a 401. Bcc recipients are kept in the raw
message. Transients are removed on uninstall.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Keep the WordPress PHPMailer when no connection uses the Google provider

Built-in API providers only make the plugin swap in Transport_PHPMailer
when a connection uses them, so SMTP-only sites are unchanged. Providers
added by other plugins keep the previous behaviour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Show the fields of the selected provider without saving

The settings and connection forms render the fields of every provider.
Those of the other providers are hidden and disabled, so they are not
submitted, and assets/js/provider-fields.js swaps them when the provider
select changes. Secrets of other providers are never printed, and a key
shared by two providers gets a unique id.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support transport-level (HTTP API) providers

2 participants