Pete Dermott
Pete Dermott

Reputation: 723

Is it possible to use XOAUTH2 through imaplib to access Google Workspace Gmail without IMAP being enabled on the domain?

I have a task to build an integration with Gmail that will collect emails from a users inbox and store them within a Django system. The client I'm working with does not allow IMAP to be enabled on their Google Workspace account.

The following code runs but generates a An error occurred: [ALERT] IMAP access is disabled for your domain. Please contact your domain administrator for questions about this feature. (Failure) error.

I've looked all over the Google Workspace admin but haven't found any way to enable access for this.

Is this even possible? I've been told that since XOAUTH2 is an authentication method I'm getting blocked at the domain level and there is going to be no way this will ever work.

My current (rough) code looks like this:

from imaplib import IMAP4_SSL
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import os.path
import pickle


def get_gmail_oauth_credentials():
    SCOPES = ['https://mail.google.com/']
    creds = None

    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)

    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json',
                SCOPES
            )
            # This will open the browser for user consent
            creds = flow.run_local_server(port=0)

        # Save the credentials for future runs
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    return creds


def connect_to_gmail_imap(user_email):
    # Get OAuth2 credentials
    creds = get_gmail_oauth_credentials()

    auth_string = f'user={user_email}\1auth=Bearer {creds.token}\1\1'

    # Connect to Gmail's IMAP server
    imap_conn = IMAP4_SSL('imap.gmail.com')

    # Authenticate using XOAUTH2
    imap_conn.authenticate('XOAUTH2', lambda x: auth_string)

    return imap_conn


if __name__ == '__main__':
    # Replace with your Gmail address
    USER_EMAIL = '[email protected]'

    try:
        imap = connect_to_gmail_imap(USER_EMAIL)
        print("Successfully connected to Gmail!")

        # Example: List all mailboxes
        typ, mailboxes = imap.list()
        if typ == 'OK':
            print("\nAvailable mailboxes:")
            for mailbox in mailboxes:
                print(mailbox.decode())

        imap.select('INBOX')
        typ, messages = imap.search(None, 'RECENT')
        if typ == 'OK':
            print(f"\nFound {len(messages[0].split())} recent messages")

        imap.logout()

    except Exception as e:
        print(f"An error occurred: {e}")

Upvotes: 0

Views: 16

Answers (0)

Related Questions