|
| 1 | +import imaplib |
| 2 | +import email |
| 3 | +from email.header import decode_header |
| 4 | +import re |
| 5 | +from typing import Optional |
| 6 | +import os |
| 7 | + |
| 8 | +def get_latest_token_from_email( |
| 9 | + imap_server: str, |
| 10 | + email_user: str, |
| 11 | + email_pass: str, |
| 12 | + mailbox: str = "INBOX", |
| 13 | + search_subject: Optional[str] = None, |
| 14 | + token_regex: str = r"\\b\d{6}\\b" |
| 15 | +) -> Optional[str]: |
| 16 | + """ |
| 17 | + Pobiera najnowszy token (np. kod 2FA) ze skrzynki email. |
| 18 | + :param imap_server: adres serwera IMAP |
| 19 | + :param email_user: login do skrzynki |
| 20 | + :param email_pass: hasło do skrzynki |
| 21 | + :param mailbox: skrzynka (domyślnie INBOX) |
| 22 | + :param search_subject: opcjonalny filtr po temacie |
| 23 | + :param token_regex: regex do wyłuskania tokenu (domyślnie 6-cyfrowy kod) |
| 24 | + :return: token lub None |
| 25 | + """ |
| 26 | + mail = imaplib.IMAP4_SSL(imap_server) |
| 27 | + mail.login(email_user, email_pass) |
| 28 | + mail.select(mailbox) |
| 29 | + search_criteria = '(UNSEEN)' |
| 30 | + if search_subject: |
| 31 | + search_criteria = f'(UNSEEN SUBJECT "{search_subject}")' |
| 32 | + status, messages = mail.search(None, search_criteria) |
| 33 | + if status != 'OK': |
| 34 | + return None |
| 35 | + for num in reversed(messages[0].split()): |
| 36 | + status, data = mail.fetch(num, '(RFC822)') |
| 37 | + if status != 'OK': |
| 38 | + continue |
| 39 | + msg = email.message_from_bytes(data[0][1]) |
| 40 | + if msg.is_multipart(): |
| 41 | + for part in msg.walk(): |
| 42 | + if part.get_content_type() == "text/plain": |
| 43 | + body = part.get_payload(decode=True).decode(errors='ignore') |
| 44 | + break |
| 45 | + else: |
| 46 | + continue |
| 47 | + else: |
| 48 | + body = msg.get_payload(decode=True).decode(errors='ignore') |
| 49 | + match = re.search(token_regex, body) |
| 50 | + if match: |
| 51 | + return match.group(0) |
| 52 | + return None |
0 commit comments