import base64
import poplib
import re
import time
from email import message_from_bytes # Для разбора содержимого письма
Функция для генерации строки аутентификации OAuth2
def generate_auth_string(user, token):
auth_string = f"user={user}\1auth=Bearer {token}\1\1"
return auth_string
POP3 параметры
pop3_server = 'outlook.office365.com'
pop3_port = 995 # POP3 over SSL
Функция подключения к POP3 и чтения писем
def connect_pop3(email, access_token):
try:
server = poplib.POP3_SSL(pop3_server, pop3_port)
# Используем OAuth2 аутентификацию
auth_string = generate_auth_string(email, access_token)
encoded_auth_string = base64.b64encode(auth_string.encode("utf-8")).decode("utf-8")
server._shortcmd(f'AUTH XOAUTH2')
server._shortcmd(f'{encoded_auth_string}')
# Получаем список писем
num_messages = len(server.list()[1])
print(f"There are {num_messages} emails in the inbox for {email}.")
# Читаем и парсим содержимое каждого письма
for i in range(num_messages):
response, lines, octets = server.retr(i + 1)
msg_content = b"\n".join(lines)
# Разбираем содержимое письма с помощью библиотеки email
msg = message_from_bytes(msg_content)
# Извлечение заголовков
subject = msg.get('Subject', 'No Subject')
from_ = msg.get('From', 'Unknown Sender')
date = msg.get('Date', 'Unknown Date')
print(f"Email {i + 1} for {email}:")
print(f"From: {from_}")
print(f"Subject: {subject}")
print(f"Date: {date}")
# Извлечение содержимого письма
if msg.is_multipart():
for part in msg.walk():
content_type = part.get_content_type()
if content_type == 'text/plain':
print("Text content:")
print(part.get_payload(decode=True).decode("utf-8"))
elif content_type == 'text/html':
print("HTML content:")
print(part.get_payload(decode=True).decode("utf-8"))
else:
print("Message content:")
print(msg.get_payload(decode=True).decode("utf-8"))
print("=" * 50)
server.quit()
except Exception as e:
print(f"Error connecting to {email}: {e}")
Функция для извлечения данных с помощью регулярного выражения
def extract_email_and_token(text):
email_pattern = r'"Email":"(.?)"'
token_pattern = r'"AccessToken":"(.?)"'
email_match = re.search(email_pattern, text)
token_match = re.search(token_pattern, text)
if email_match and token_match:
email = email_match.group(1)
access_token = token_match.group(1)
return email, access_token
else:
return None, None
Чтение строк по одной и обработка
def process_lines_from_file(file_path, pause_duration=5):
try:
with open(file_path, 'r', encoding='utf-8') as file:
for line in file:
line = line.strip() # Убираем лишние пробелы и пустые строки
if line: # Пропуск пустых строк
email, access_token = extract_email_and_token(line)
if email and access_token:
print(f"Processing email: {email}")
connect_pop3(email, access_token)
# Пауза перед обработкой следующей строки
time.sleep(pause_duration)
else:
print(f"Could not extract data from line: {line}")
except Exception as e:
print(f"An error occurred while reading the file: {e}")
Укажите путь к вашему текстовому файлу
file_path = "Путь к вашему файлу с почтами в формате JSON"
Обработка всех строк в файле с паузой в 5 секунд между запросами
process_lines_from_file(file_path, pause_duration=5)