How to Connect Hotmail & Outlook IMAP with OAuth2 Refresh Tokens in Python
Step-by-step Python 3 guide to exchanging Microsoft OAuth2 refresh_token and client_id for an access token and reading Hotmail/Outlook mail via imaplib XOAUTH2.
1. Why Microsoft Deprecated Basic IMAP Passwords
Microsoft disabled basic username/password IMAP authentication on consumer @hotmail.com and @outlook.com mailboxes. Modern automation scripts must authenticate via OAuth2 (XOAUTH2) using a delegated refresh_token and client_id.
2. MailStock Credential Format
Every OAuth2 account delivered by MailStock arrives in one clean pipe-separated line: email|password|refresh_token|client_id. You only need email, refresh_token, and client_id to mint fresh short-lived access tokens anytime.
3. Working Python 3 XOAUTH2 Example (No External Libraries Needed)
import imaplib
import json
import urllib.parse
import urllib.request
def refresh_access_token(client_id: str, refresh_token: str) -> str:
url = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
payload = urllib.parse.urlencode({
"client_id": client_id,
"refresh_token": refresh_token,
"grant_type": "refresh_token",
"scope": "https://outlook.office.com/IMAP.AccessAsUser.All offline_access",
}).encode("utf-8")
req = urllib.request.Request(url, data=payload, method="POST")
with urllib.request.urlopen(req, timeout=15) as resp:
return json.loads(resp.read().decode("utf-8"))["access_token"]
def read_inbox(line: str):
email, _pw, refresh_token, client_id = line.strip().split("|")
access_token = refresh_access_token(client_id, refresh_token)
auth_str = f"user={email}\x01auth=Bearer {access_token}\x01\x01".encode("utf-8")
with imaplib.IMAP4_SSL("outlook.office.com", 993) as imap:
imap.authenticate("XOAUTH2", lambda _: auth_str)
imap.select("INBOX")
status, data = imap.search(None, "ALL")
print(email, "message count:", len(data[0].split()))
4. Common Pitfalls & Best Practices
Always connect consumer @hotmail.com and @outlook.com accounts to outlook.office.com:993 (not outlook.office365.com). Cache the returned access_token for ~45 minutes before refreshing to minimize token endpoint requests.