import base64 import smtplib def encode_xoauth2(username, access_token): # Define the format as specified xoauth2_format = f"user={username}\x01auth=Bearer {access_token}\x01\x01" # Encode the format to base64 base64_encoded = base64.b64encode(xoauth2_format.encode()).decode() return base64_encoded def authenticate_smtp_xoauth2(email_address, access_token): # SMTP server configuration smtp_server = "smtp.office365.com" smtp_port = 587 # Create the SMTP connection server = smtplib.SMTP(smtp_server, smtp_port) server.set_debuglevel(1) # Enable debug output for detailed logs # Send the EHLO command server.ehlo() # Start TLS for security server.starttls() # Send the EHLO command again after STARTTLS server.ehlo() # Encode the credentials auth_string = f"user={email_address}\x01auth=Bearer {access_token}\x01\x01" auth_encoded = base64.b64encode(auth_string.encode()).decode() try: # Send the AUTH XOAUTH2 command server.putcmd("AUTH XOAUTH2") # Read the server's response code, response = server.getreply() if code == 334: # Send the encoded credentials server.putcmd(auth_encoded) # Read the server's response code, response = server.getreply() if code == 235: print("Authentication successful.") else: print(f"Authentication failed: {response.decode()}") else: print(f"AUTH XOAUTH2 command not accepted: {response.decode()}") except smtplib.SMTPAuthenticationError as e: print(f"Authentication failed: {e.smtp_error.decode()}") finally: # Quit the SMTP server server.quit() # Predefined variables email_address = "" access_token = "..----" #email_address = "test@contoso.onmicrosoft.com" #access_token = "EwBAAl3BAAUFFpUAo7J3Ve0bjLBWZWCclRC3EoAA" # Authenticate with the SMTP server authenticate_smtp_xoauth2(email_address, access_token)