mailledger-oauth
OAuth2 authentication library for email protocols (IMAP/SMTP).
Features
- ✅ Authorization Code Flow with PKCE support (RFC 7636)
- ✅ Device Flow for CLI/IoT applications (RFC 8628)
- ✅ Token Management with automatic expiration tracking
- ✅ Token Refresh capability
- ✅ SASL Mechanisms: XOAUTH2 (Google/Microsoft) and OAUTHBEARER (RFC 7628)
- ✅ Pre-configured Providers: Gmail, Outlook/Microsoft 365, Yahoo
- ✅ Custom Provider support
Quick Start
Prerequisites
For Microsoft Outlook/Office 365:
- Register application at Azure Portal
- Configure redirect URI (e.g.,
http://localhost:8080) - Note your Application (client) ID
- Obtain necessary permissions (IMAP.AccessAsUser.All, SMTP.Send, offline_access)
For Gmail:
- Create project at Google Cloud Console
- Enable Gmail API
- Configure OAuth consent screen
- Create OAuth 2.0 credentials
- Add
https://mail.google.com/scope
Authorization Code Flow (Desktop Apps)
use ;
async
Using with IMAP
use ;
use ;
async
Token Storage
Store tokens securely using the credential storage:
use ;
// Store token
let account_id = new;
store_oauth_token?;
// Retrieve token later
let stored_token = get_oauth_token?;
// Delete token
delete_oauth_token?;
Token Refresh
// Check if token is expired (with 60-second buffer)
if token.is_expired
Device Flow (CLI/IoT Apps)
For applications that can't easily open a browser:
use ;
async
Providers
Microsoft Outlook/Office 365
let provider = microsoft?;
// Scopes:
// - https://outlook.office365.com/IMAP.AccessAsUser.All
// - https://outlook.office365.com/SMTP.Send
// - offline_access (for refresh tokens)
Gmail
let provider = google?;
// Scope: https://mail.google.com/
Yahoo
let provider = yahoo?;
// Scopes: mail-r, mail-w
Custom Provider
let provider = new?
.with_default_scopes;
SASL Mechanisms
XOAUTH2 (Google/Microsoft)
use xoauth2_response;
let auth_string = xoauth2_response;
// Use with IMAP: AUTHENTICATE XOAUTH2 {auth_string}
OAUTHBEARER (RFC 7628)
use oauthbearer_response;
let auth_string = oauthbearer_response;
// Use with IMAP: AUTHENTICATE OAUTHBEARER {auth_string}
Examples
Run the Outlook OAuth2 example:
Security Notes
- Always use PKCE for desktop/mobile applications (enabled by default with
.with_pkce()) - Store tokens securely using system keyring (see
mailledger-core::credentials) - Never commit client secrets or tokens to version control
- Validate state parameter to prevent CSRF attacks
- Use TLS for all token exchanges
Why OAuth2?
Microsoft will permanently disable Basic Authentication (username/password) for IMAP/SMTP in April 2026. OAuth2 is now mandatory for accessing Outlook/Microsoft 365 email accounts.
Benefits:
- ✅ No passwords stored in the app
- ✅ Granular permission scopes
- ✅ Token expiration and refresh
- ✅ User can revoke access anytime
- ✅ Complies with modern security standards