For years the standard way to send mail through a mailbox provider was simple: connect to the SMTP server, log in with the account's username and password and submit the message. Large providers have been withdrawing that method. Passwords are easily phished, reused and leaked, and a password sent by a script grants full access to the mailbox. The replacement is OAuth 2.0, where the application receives a limited, expiring token instead of the password. Many integrations broke when the change reached them, with errors such as 535 5.7.139 Authentication unsuccessful, basic authentication is disabled at Microsoft 365 or "Username and Password not accepted" at Google. This guide explains why the change happened, how OAuth 2.0 for SMTP works through the XOAUTH2 mechanism, what you must set up in the provider's admin console, how to implement it with libraries, how to handle token expiry, the errors you will meet and when it is wiser to avoid mailbox SMTP altogether and use a purpose-built sending service. Provider policies change often, so confirm the current rules in their documentation.
Why passwords are being retired
- Phishing and reuse. A stolen mailbox password gives access to everything the account can do, not only to sending.
- No second factor. Basic authentication in a script cannot prompt for multi-factor authentication, so accounts used for SMTP often stay on weaker protection.
- No granular control. A password cannot be limited to "send mail only" or revoked for one application without changing it for all.
- Credential-stuffing attacks target legacy protocols because they lack modern defences.
OAuth 2.0 addresses these: the token is issued to a specific application, covers specific permissions (scopes), expires after a short time and can be revoked centrally. Providers have announced and enforced the end of basic authentication for several protocols over the last years; check the current status for your tenant and account type in the provider documentation.
How XOAUTH2 works
SMTP supports pluggable authentication mechanisms advertised in the EHLO response. XOAUTH2 lets the client send the user name and an OAuth access token in a single base64-encoded string:
AUTH XOAUTH2 base64("user=" + email + "^Aauth=Bearer " + access_token + "^A^A")
; ^A is the control character 0x01The server validates the token with the identity provider, checks that it is valid for SMTP sending and that it belongs to the stated mailbox, and accepts or refuses. The access token lasts typically for an hour; a longer-lived refresh token lets the application request new access tokens without involving the user. See SMTP authentication methods for the other mechanisms.
Flow overview
- Register the application in the provider's console (Google Cloud for Gmail, Microsoft Entra ID for Microsoft 365). You receive a client ID and create a client secret or certificate.
- Choose permissions. For Gmail the scope is
https://mail.google.com/for SMTP; a narrowergmail.sendscope applies to the Gmail API instead. For Microsoft 365, SMTP uses theSMTP.Sendpermission (delegated or application, depending on the flow) for the Exchange Online resource. - Get consent. A user (delegated flow) or an administrator (application flow) grants the permission. Organisations may restrict which apps can request consent.
- Obtain tokens. In a delegated flow the user signs in once and the app stores a refresh token. In an application (client credentials) flow, the app requests tokens as itself for allowed mailboxes.
- Authorise the mailbox. In Microsoft 365, SMTP AUTH must be enabled for the mailbox or tenant, and for application flows a service principal must be granted access to the mailbox in Exchange Online.
- Connect and authenticate. Use port 587 with STARTTLS (or 465 where offered) and AUTH XOAUTH2 with a fresh access token.
- Renew tokens before expiry, store refresh tokens and secrets securely and handle revocation.
Library examples
// Node.js with Nodemailer: OAuth2 transport (Gmail)
const transport = nodemailer.createTransport({
host: 'smtp.gmail.com', port: 465, secure: true,
auth: {
type: 'OAuth2',
user: '[email protected]',
clientId: process.env.OAUTH_CLIENT_ID,
clientSecret: process.env.OAUTH_CLIENT_SECRET,
refreshToken: process.env.OAUTH_REFRESH_TOKEN // library obtains access tokens
}
});
# Python: build the XOAUTH2 string for smtplib
import base64, smtplib
def xoauth2(user, token):
return base64.b64encode(f"user={user}\x01auth=Bearer {token}\x01\x01".encode()).decode()
s = smtplib.SMTP("smtp.office365.com", 587)
s.starttls()
s.docmd("AUTH", "XOAUTH2 " + xoauth2("[email protected]", access_token))Libraries differ in how much they automate. Nodemailer refreshes access tokens when given a refresh token and client details; with smtplib you must fetch and refresh tokens yourself with an OAuth library. Keep the secrets in a secure store, not in source code, and rotate them. See Nodemailer guide and Python smtplib.
Common errors
| Error | Likely cause | Fix |
|---|---|---|
| 535 5.7.139 / 5.7.30 basic authentication is disabled | Tenant or account no longer accepts passwords for SMTP | Move to OAuth 2.0 or a relay; do not wait for exceptions |
| 535 5.7.3 Authentication unsuccessful with a valid token | Token lacks the SMTP scope, wrong audience, or the mailbox is not authorised | Check scopes, consent and mailbox permission |
| 534 5.7.9 Application-specific password required | Account uses two-step verification and a password was used | Use OAuth or a relay, not the account password. See Gmail SMTP settings and app passwords |
| invalid_grant when refreshing | Refresh token revoked, expired from inactivity or password changed | Repeat consent; handle the error by alerting an administrator |
| SmtpClientAuthentication is disabled for the Tenant | SMTP AUTH turned off in Microsoft 365 | An administrator enables it for the mailbox, or use another route. See Microsoft 365 SMTP settings |
| Token expired mid-session | Long-lived connection outlasted the access token | Get a new token before each connection; see connection pooling |
| Sending limits reached | Mailbox quotas apply regardless of auth method | See Google Workspace relay limits |
Should you send application mail through a mailbox at all?
Mailbox SMTP is built for people using mail clients. It has low sending limits, sends from a personal or shared mailbox, ties your application to one person's account and changes whenever the provider updates its security policy. For transactional and bulk mail from an application, a sending service is a better fit: a relay or API with its own credentials, domain authentication, higher limits, bounce handling and logs. You then do not need OAuth for each mailbox. See SMTP vs API, Microsoft 365 relay options and when to move from Google Workspace relay. Keep OAuth for the cases where mail must truly go out from a person's mailbox, such as a mail client or a tool that sends on behalf of users, see Send As vs Send on Behalf.
Security practices
- Request the narrowest scope and the fewest mailboxes.
- Store client secrets and refresh tokens in a secrets manager and encrypt them at rest.
- Prefer certificates or managed identities over long-lived client secrets where the platform allows.
- Log token requests and sending, and alert on failures and unusual volume.
- Review app consents regularly and remove unused apps.
- Plan for credential rotation and for revocation if a token leaks. See API key security and rotation.
OAuth 2.0 adds moving parts to SMTP, but the pieces are well defined: register, consent, get tokens, send with XOAUTH2 and renew. If your mail comes from an application, consider whether a sending service would spare you this machinery altogether.
Send without managing mailbox tokens Use a dedicated relay or API credential for application mail.
References and further reading
Frequently asked questions
Why does SMTP with my password no longer work at Microsoft 365 or Gmail?
Providers disabled basic authentication for security reasons. Use OAuth 2.0 with XOAUTH2, or a different sending route.
What is XOAUTH2?
An SMTP authentication mechanism that sends the user name and an OAuth access token instead of a password.
How often do I need a new access token?
Access tokens usually last about an hour. Use a refresh token to get new ones before each connection.
Do I need OAuth if I use an SMTP relay service?
No. A relay uses its own credential or API key. OAuth is needed mainly for sending directly through a person's mailbox.
What causes invalid_grant when refreshing a token?
The refresh token was revoked or expired, or the account changed. Repeat the consent flow.