Every WordPress developer who has implemented email functionality through Gmail’s API using the WP Mail SMTP plugin knows how convenient and secure it is—until something breaks. One of the most subtle yet catastrophic issues that can occur is the expiry of OAuth tokens. This is exactly what happened when a sudden surge of undelivered emails revealed that Gmail API sending via WP Mail SMTP had stopped working silently. This article walks through how OAuth token expiry disrupted email functionality and how an automatic token renewal workflow was implemented to resolve it.
TLDR:
When Gmail API sending via WP Mail SMTP silently stopped working, expired OAuth tokens were the underlying cause. Because the token renewal mechanism wasn’t handling refreshes properly, it led to failed email deliveries without notification. A background cron job-based workflow was implemented to detect token expiry, refresh tokens proactively, and log the status for better visibility. This solution re-enabled seamless email sending and provided long-term stability.
What Went Wrong with OAuth Tokens
The root of the problem lay in how WP Mail SMTP handled Gmail’s OAuth tokens. When a user connects their Gmail account, Google provides an access token and a refresh token. The access token has a limited lifespan—usually 60 minutes—and must be periodically refreshed using the refresh token.
In theory, WP Mail SMTP manages this renewal silently in the background. But in practice, the auto-refresh mechanism failed silently on a few WordPress installations. When the access token expired and the plugin failed to refresh it, all outgoing emails got stuck or failed to send. There were no visible errors to the admin because many sites lacked proper logging mechanisms.
Symptoms and Diagnostic Process
The symptoms ranged from emails not sending at all to WP events (contact form submissions, password resets, etc.) being lost entirely. Here’s how the issue manifested:
- Emails appeared to “send” from the admin panel, but recipients never received them.
- No bouncebacks or Gmail error messages were shown inside WordPress.
- The OAuth info in the WP Mail SMTP settings looked valid but wasn’t functional.
The breakthrough came from analyzing the wp_mail logs and using Gmail API’s diagnostic console. The plugin was still trying to send emails with expired access tokens, and the Gmail API was rejecting them with a 401 error—unauthorized due to token expiration.
Root Cause Investigation
The crucial insight was discovering that the refresh token stored in the WordPress database was never being used appropriately to get new access tokens. In some cases, the refresh token itself had also become invalid, either due to:
- Removal of app permissions in Google account settings.
- Lack of refresh cycle because the user hadn’t logged in for weeks or months.
Despite the plugin offering a UI to reconnect manually, this solution wasn’t scalable across client sites or multisite installations. A programmatic and automated solution became necessary.
The Auto-Renew Workflow Implementation
To resolve the issue, a custom auto-renew workflow was implemented using WordPress cron jobs, Gmail’s token endpoint, and logs to track success or failure. Here’s a breakdown of the process:
1. Scheduled Token Audit Job
A cron job was scheduled to run every hour using wp_schedule_event(), checking the token’s expiry time stored in the plugin’s database options. If the current time approached the token’s expiry, the token would be flagged for renewal.
2. Refresh Token API Call
The Google OAuth2 endpoint https://oauth2.googleapis.com/token was used to request a new access token using the stored refresh token.
This involved a POST request with the following information:
- client_id
- client_secret
- refresh_token
- grant_type = refresh_token
The new access token was then stored back into the WordPress database using update_option().
3. Detailed Logging
Each step of the process was logged into a custom table created using dbDelta(), storing:
- Timestamp
- Status code from the API
- New expiration time
- Error messages, if any
This gave a powerful overview of how frequently tokens were being refreshed and helped immediately pinpoint problems if the refresh call failed.
4. Fallback Email Notification
In the rare case a refresh failed, the cron job triggered an alert email to the site admin using a separate SMTP service (like SendGrid) that was configured as a fallback. This ensured that no notification ever went unseen due to the primary method being down.
Results After Implementation
Within a week of deploying this workflow, email reliability improved dramatically. Sites that previously experienced silent failures now self-healed their access tokens. The logging table began capturing successful token refreshes across intervals, and fallback alerts were rarely triggered.
Perhaps more importantly, the implementation provided peace of mind—knowing that OAuth token expiry would no longer be an invisible failure point in the email-sending stack.
Future Improvements
While the current workflow is stable, further enhancements are planned:
- Admin Dashboard Widget: Display the token’s current status and stats directly in the WordPress dashboard for visibility.
- Email Activity Monitor: Track failed emails and associate them with access token issues, if any.
- Multi-Language Alerts: Send fallback warnings in user-defined languages for international sites.
These improvements will eventually lead to a complete OAuth health-check system within the WordPress admin area.
FAQ – Frequently Asked Questions
Q: Why does Gmail require OAuth instead of a regular password for SMTP?
A: Google has tightened security measures and no longer allows basic authentication (username/password) for SMTP. OAuth is a safer method that limits scopes and permissions while allowing revocation at any time.
Q: How long does a Gmail access token last?
A: Typically, an access token lasts for about 3600 seconds (1 hour). After that, Gmail requires a new token to authenticate email sending via APIs.
Q: What happens if the refresh token becomes invalid?
A: If the refresh token is revoked (e.g., user changes password or disables the app), you’ll need to manually reauthorize the plugin with Google via the WP Mail SMTP settings page.
Q: Is this auto-renew feature available in WP Mail SMTP by default?
A: WP Mail SMTP handles token renewals, but failures can still occur silently. The auto-renew system described here is a custom implementation for added reliability.
Q: Can this implementation support other OAuth providers like Microsoft or Yahoo?
A: With adjustments to the token endpoint and scope handling, a similar cron-based system can be adapted for other OAuth 2.0 providers.
In summary, maintaining reliable email delivery via the Gmail API in WordPress requires more than just initial OAuth setup. Monitoring token health and automating token renewal is critical—and now, it’s entirely possible.