import requests import imaplib import email from email.utils import parsedate_to_datetime def get_access_token(refresh_token, client_id): url = "https://login.microsoftonline.com/common/oauth2/v2.0/token" payload = { 'client_id': client_id, 'grant_type': 'refresh_token', 'refresh_token': refresh_token, 'scope': 'https://outlook.office.com/IMAP.AccessAsUser.All', } response = requests.post(url, data=payload) if response.status_code != 200: print("Error get token:", response.json()) return None token_info = response.json() return token_info['access_token'] def fetch_emails(access_token, your_email): imap_host = 'outlook.office365.com' mail = imaplib.IMAP4_SSL(imap_host) auth_string = f"user={your_email}\x01auth=Bearer {access_token}\x01\x01" mail.authenticate('XOAUTH2', lambda x: auth_string) email_folders = ["INBOX", "Junk"] all_emails = [] for folder in email_folders: mail.select(folder) result, data = mail.search(None, 'ALL') email_ids = data[0].split() for email_id in email_ids: result, msg_data = mail.fetch(email_id, '(RFC822)') raw_email = msg_data[0][1] msg = email.message_from_bytes(raw_email) email_date = parsedate_to_datetime(msg['Date']) all_emails.append((email_date, msg)) all_emails.sort(key=lambda x: x[0], reverse=True) for email_date, msg in all_emails: print(f"Date: {email_date}") print(f"Subject: {msg['Subject']}") print(f"From: {msg['From']}") print(f"Contents of the received email:") email_body = None if msg.is_multipart(): for part in msg.walk(): content_type = part.get_content_type() if content_type == 'text/html': email_body = part.get_payload(decode=True).decode('utf-8', errors='replace') break elif content_type == 'text/plain' and email_body is None: email_body = part.get_payload(decode=True).decode('utf-8', errors='replace') else: email_body = msg.get_payload(decode=True).decode('utf-8', errors='replace') print(email_body) print("-" * 50) mail.logout() if __name__ == "__main__": your_email = "your_email@hotmail.com" refresh_token = "YOUR_REFRESH_TOKEN" client_id = "YOUR_CLIENT_ID" access_token = get_access_token(refresh_token, client_id) if access_token: fetch_emails(access_token, your_email)