OAuth 2.0 lets an application log in to a mailbox over SMTP or IMAP with a short-lived access token instead of the user's password. The client obtains the token from the mailbox provider's identity service after the user (or an administrator) grants consent, then presents it during the SMTP or IMAP login using the XOAUTH2 or OAUTHBEARER SASL mechanism. When the token expires, the application uses a refresh token to get a new one.
Large mailbox providers have been turning off or restricting passwords for third-party mail access, so many applications that worked for years now fail with an authentication error until they move to OAuth. This article explains the pieces, shows the exact protocol exchange, gives a working Python example, and lists the errors you will see. Provider-specific details such as scope names, console menus and cut-off dates change, so confirm them in the provider's current documentation.
Why providers moved to OAuth
A password gives anyone who holds it complete access, never expires on its own and cannot be limited to one task. It is also exposed to every application that stores it and to phishing and credential stuffing. An OAuth access token is scoped (for example, permission to send mail only), expires quickly, can be revoked per application without changing the password, and works with multi-factor authentication, because the user completes the sign-in on the provider's own page. The trade-off is complexity: the application must register with the provider, run a consent flow and manage tokens safely.
The moving parts
| Term | Meaning |
|---|---|
| Resource owner | The mailbox user (or, for organisation apps, an administrator who consents for all users) |
| Client application | Your software that wants to send or read mail |
| Authorization server | The provider's identity service that issues tokens |
| Client ID and secret | Identifiers you receive when you register the application |
| Scope | The permission requested, such as send mail or IMAP access. Names are provider-specific |
| Access token | Short-lived credential presented in the SMTP or IMAP login |
| Refresh token | Longer-lived credential used to obtain new access tokens. Treat it like a password |
| Redirect URI | Where the provider returns the authorisation code after consent |
How a user-consent flow works
- Register the application in the provider's developer or admin console and note the client ID. Add the exact redirect URI.
- Send the user to the provider's authorization endpoint with your client ID, redirect URI, requested scopes and a random state value. Use PKCE for public clients.
- The user signs in on the provider's page and approves the requested permissions.
- The provider redirects back with an authorization code.
- Your server exchanges the code at the token endpoint and receives an access token and, if you requested offline access, a refresh token.
- Store the refresh token encrypted. Use the access token for SMTP or IMAP login, and refresh it before it expires.
The generic framework is defined in RFC 6749. Unattended services (no user present) use different grants, and the options available for SMTP or IMAP differ by provider, so check which flow the provider supports for mailbox protocols before designing around it.
What XOAUTH2 looks like on the wire
XOAUTH2 is a SASL mechanism that carries the user name and bearer token in one initial response. The string is built from the user, the token and two control characters (byte value 1), then base64 encoded for transmission:
[email protected]^Aauth=Bearer ya29.EXAMPLE^A^A
(^A is the byte 0x01. The whole string is base64 encoded.)C: AUTH XOAUTH2 dXNlcj1zb21lb25lQGV4YW1wbGUuY29tAWF1dGg9QmVhcmVyIHlhMjkuRVhBTVBMRQEB
S: 235 2.7.0 Accepted
(on failure)
S: 334 eyJzdGF0dXMiOiI0MDEi... <- base64 JSON describing the error
C: <- empty line
S: 535 5.7.8 Authentication failedOn failure, many servers return a 334 challenge containing a JSON error. The client must reply with an empty line before the server sends the final 535. OAUTHBEARER (RFC 7628) is the standardised sibling: similar idea, a formal message format and a defined error structure. Which of the two a server offers appears in the AUTH line of its EHLO response. For the broader family of mechanisms see SMTP authentication mechanisms.
A working Python example
import smtplib, ssl
from email.message import EmailMessage
def xoauth2(user, token):
return 'user=%s\x01auth=Bearer %s\x01\x01' % (user, token)
user = '[email protected]'
token = get_fresh_access_token() # your code: refresh if expired
msg = EmailMessage()
msg['From'] = user
msg['To'] = '[email protected]'
msg['Subject'] = 'OAuth test'
msg.set_content('Sent with an access token.')
ctx = ssl.create_default_context()
with smtplib.SMTP('smtp.provider.example', 587) as s:
s.ehlo()
s.starttls(context=ctx)
s.ehlo()
s.auth('XOAUTH2', lambda challenge=None: xoauth2(user, token),
initial_response_ok=True)
s.send_message(msg)Replace smtp.provider.example with the host named in your provider's documentation and obtain the token from their token endpoint. Never log the token. For IMAP the same string is used with the AUTHENTICATE XOAUTH2 command, for example through imaplib.IMAP4_SSL.authenticate().
Token handling rules
- Refresh early. Access tokens are short-lived, commonly around an hour, but lifetimes are provider-defined. Refresh a few minutes before expiry rather than after a failure.
- Protect refresh tokens. Encrypt at rest, restrict access, and never commit them to source control.
- Request minimum scopes. Ask for send-only access if you do not read mail.
- Handle revocation. If the user removes consent or changes the password in some environments, refresh fails; prompt for a new sign-in.
- One token per mailbox. Do not share a token across users.
Mailbox OAuth versus relay credentials
OAuth for SMTP is for sending as a mailbox through that mailbox provider, subject to its sending limits and policies. It is not designed for high-volume application mail. For transactional and marketing volume, use a dedicated relay or API with its own credentials, and authenticate your domain. Compare approaches in SMTP versus API. Sending through a relay such as MigoSMTP uses SMTP credentials or an API key over TLS, so there is no mailbox consent flow to build.
Provider notes
Each mailbox provider has its own rules. Google has restricted password-based access for many accounts and expects OAuth or app passwords where allowed; see Gmail SMTP settings. Microsoft has been retiring basic authentication in Exchange Online for protocols such as IMAP and has announced the same direction for SMTP client submission on a published schedule; read SMTP AUTH disabled in Microsoft 365 and the current Microsoft documentation for the timeline and the OAuth scopes for SMTP and IMAP. Do not rely on a date quoted in an article, including this one.
Troubleshooting
| Error or symptom | Likely cause | Fix |
|---|---|---|
| 535 5.7.8 Authentication unsuccessful | Expired or invalid token, wrong user | Refresh the token; make sure the user in the string matches the token owner |
| 534 or 535 with a JSON challenge | Token missing required scope | Request the correct SMTP or IMAP scope and ask the user to consent again |
| invalid_grant at the token endpoint | Refresh token revoked or expired, or clock skew | Re-run the consent flow; check server time |
| invalid_client | Wrong client ID or secret, or wrong tenant | Check the application registration |
| redirect_uri_mismatch | Redirect URI differs from registered value | Match scheme, host, path and port exactly |
| AUTH XOAUTH2 not advertised | Wrong host or port, or mechanism disabled | Read the EHLO response; ask the administrator to enable it |
| Works for the admin, fails for users | Tenant policy or missing admin consent | Obtain admin consent or adjust the policy |
| Basic auth stopped working | Provider disabled passwords | Migrate to OAuth or a relay with its own credentials; see 535 authentication failed |
Summary and next steps
Register your application, run the consent flow once per mailbox, store the refresh token securely, refresh before expiry and build the XOAUTH2 string only at login time. If you only need to send application mail from your own domain, a relay or API is simpler and avoids mailbox limits.
No consent flows needed Send from your own domain with SMTP credentials or an API key.
References and further reading
Frequently asked questions
What is XOAUTH2?
A SASL mechanism that sends the user name and an OAuth 2.0 bearer token in the SMTP or IMAP login instead of a password.
What is the difference between XOAUTH2 and OAUTHBEARER?
OAUTHBEARER is the standardised mechanism in RFC 7628, while XOAUTH2 is an older, widely deployed format that works similarly.
How long do OAuth access tokens last?
They are short-lived and the lifetime is set by the provider, often around an hour; use the refresh token to obtain new ones.
Why did my SMTP login stop working?
The provider may have disabled password or basic authentication for that protocol; move to OAuth or another supported method.
Do I need OAuth to send through an SMTP relay service?
No. Relay services normally use SMTP credentials or API keys over TLS rather than mailbox OAuth.