import imaplib
import hashlib

# Configuration
IMAP_SERVER = 'your_server_IP'
IMAP_PORT = 993
MASTER_PASSWORD = 'as_configured_in_webadminUI'
USER_MAILBOX = 'target_mailbox'

def master_authenticate(imap_connection, master_password):
    imap_connection.send(b'a X-MASTERAUTH\r\n')
    response = imap_connection.readline()
    challenge = response.split(b'+ ')[1].strip().decode()

    # Compute MD5 of challenge string concatenated with master password
    md5_hash = hashlib.md5((challenge + master_password).encode()).hexdigest()
    imap_connection.send((md5_hash + '\r\n').encode())
    response = imap_connection.readline().decode()

    if 'OK X-MASTERAUTH' in response:
        print("Master authentication successful.")
        return True
    else:
        print("Master authentication failed.")
        return False

def set_user_account(imap_connection, user_mailbox):
    imap_connection.send(f'b X-SETUSER "{user_mailbox}"\r\n'.encode())
    response = imap_connection.readline().decode()
    if 'OK X-SETUSER' in response:
        print(f"Switched to user {user_mailbox}.")
    else:
        print(f"Failed to switch to user {user_mailbox}.")

def test_master_authentication():
    try:
        imap_connection = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT)
        
        if master_authenticate(imap_connection, MASTER_PASSWORD):
            set_user_account(imap_connection, USER_MAILBOX)

        imap_connection.logout()
    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == '__main__':
    test_master_authentication()
