#!/usr/bin/env python3 """ Gmail OAuth2 Refresh Token Generator for Vaultwarden This script helps you generate a refresh token for Gmail SMTP OAuth2 authentication. """ from google_auth_oauthlib.flow import InstalledAppFlow import sys SCOPES = ['https://www.googleapis.com/auth/gmail.send'] def get_refresh_token(client_id, client_secret): """Generate OAuth2 refresh token for Gmail""" client_config = { "installed": { "client_id": client_id, "client_secret": client_secret, "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "redirect_uris": ["http://localhost:8080/"] } } print("=" * 70) print("Gmail OAuth2 Refresh Token Generator") print("=" * 70) print() print("IMPORTANT: Make sure you've added this redirect URI to your Google Cloud Console:") print(" http://localhost:8080/") print() print("A browser window will open for you to authorize the application.") print("Please sign in with your Google Workspace account and grant access.") print() try: flow = InstalledAppFlow.from_client_config(client_config, SCOPES) creds = flow.run_local_server(port=8080) print() print("=" * 70) print("SUCCESS! OAuth2 credentials obtained") print("=" * 70) print() print("Add these to your Vaultwarden .env file:") print() print(f"SMTP_AUTH_MECHANISM=Xoauth2") print(f"SMTP_OAUTH2_CLIENT_ID={client_id}") print(f"SMTP_OAUTH2_CLIENT_SECRET={client_secret}") print(f"SMTP_OAUTH2_REFRESH_TOKEN={creds.refresh_token}") print() print("=" * 70) except Exception as e: print(f"Error: {e}", file=sys.stderr) sys.exit(1) if __name__ == "__main__": print() print("Please enter your Google Cloud OAuth2 credentials:") print("(You can get these from https://console.cloud.google.com)") print() client_id = input("Enter your OAuth2 Client ID: ").strip() client_secret = input("Enter your OAuth2 Client Secret: ").strip() if not client_id or not client_secret: print("Error: Both Client ID and Client Secret are required!", file=sys.stderr) sys.exit(1) get_refresh_token(client_id, client_secret)