New guide: how to warm up a dedicated IP without hurting your reputation. Read now →
Log in
MigoSMTP
SMTP and APIUpdated 26 Oct 2026

SMTP OAuth 2.0: Replacing Passwords for Gmail and Microsoft 365 Sending

Why Gmail and Microsoft 365 have moved away from basic password authentication for SMTP, how OAuth 2.0 with XOAUTH2 works, app registration and tokens, library examples, and when an SMTP relay or API key is simpler.

KM
Written by Karan Malhotra
API and Developer Experience Lead
Reviewed by Jonas Lindqvist
  • Published20 Oct 2025
  • Read time6 min
  • Length1,266 words
Share this guide

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.

Old wayUsername and password (basic authentication) over SMTP AUTH PLAIN or LOGIN
New wayOAuth 2.0 access token presented with the XOAUTH2 mechanism; tokens expire and are scoped
You needAn app registration, consent or admin approval, a refresh token flow and code that renews tokens
AlternativeFor application mail, use an SMTP relay or API with a dedicated credential instead of a person's mailbox

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 0x01

The 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

  1. 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.
  2. Choose permissions. For Gmail the scope is https://mail.google.com/ for SMTP; a narrower gmail.send scope applies to the Gmail API instead. For Microsoft 365, SMTP uses the SMTP.Send permission (delegated or application, depending on the flow) for the Exchange Online resource.
  3. Get consent. A user (delegated flow) or an administrator (application flow) grants the permission. Organisations may restrict which apps can request consent.
  4. 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.
  5. 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.
  6. Connect and authenticate. Use port 587 with STARTTLS (or 465 where offered) and AUTH XOAUTH2 with a fresh access token.
  7. 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

ErrorLikely causeFix
535 5.7.139 / 5.7.30 basic authentication is disabledTenant or account no longer accepts passwords for SMTPMove to OAuth 2.0 or a relay; do not wait for exceptions
535 5.7.3 Authentication unsuccessful with a valid tokenToken lacks the SMTP scope, wrong audience, or the mailbox is not authorisedCheck scopes, consent and mailbox permission
534 5.7.9 Application-specific password requiredAccount uses two-step verification and a password was usedUse OAuth or a relay, not the account password. See Gmail SMTP settings and app passwords
invalid_grant when refreshingRefresh token revoked, expired from inactivity or password changedRepeat consent; handle the error by alerting an administrator
SmtpClientAuthentication is disabled for the TenantSMTP AUTH turned off in Microsoft 365An administrator enables it for the mailbox, or use another route. See Microsoft 365 SMTP settings
Token expired mid-sessionLong-lived connection outlasted the access tokenGet a new token before each connection; see connection pooling
Sending limits reachedMailbox quotas apply regardless of auth methodSee 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.

Explore the SMTP relay

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.

Topics#oauth2#xoauth2#gmail#microsoft 365#authentication
Was this guide helpful?Your answer helps us improve our documentation.

Start sending in minutes.

Create an account, add your domain and send your first email.

Get started Talk to sales