scripts/mail-check: fix typing issues

Replaces the body payload parsing with proper handling for multipart
messages.
This commit is contained in:
Martin Weinelt 2025-05-08 01:13:15 +02:00
parent 313f94ed8f
commit 1615c93511
No known key found for this signature in database
GPG Key ID: 87C1E9888F856759

View File

@ -7,6 +7,7 @@ from datetime import datetime, timedelta
import email import email
import email.utils import email.utils
import time import time
from typing import cast
RETRY = 100 RETRY = 100
@ -84,7 +85,7 @@ def _read_mail(
for _ in range(0, RETRY): for _ in range(0, RETRY):
print("Retrying") print("Retrying")
obj.select() obj.select()
typ, data = obj.search(None, '(SINCE %s) (SUBJECT "%s")'%(dt, subject)) _, data = obj.search(None, '(SINCE %s) (SUBJECT "%s")' % (dt, subject))
if data == [b'']: if data == [b'']:
time.sleep(1) time.sleep(1)
continue continue
@ -99,12 +100,21 @@ def _read_mail(
if delete: if delete:
obj.store(uid, '+FLAGS', '\\Deleted') obj.store(uid, '+FLAGS', '\\Deleted')
obj.expunge() obj.expunge()
message = email.message_from_bytes(raw[0][1]) assert raw[0] and raw[0][1]
message = email.message_from_bytes(cast(bytes, raw[0][1]))
print("Message with subject '%s' has been found" % message['subject']) print("Message with subject '%s' has been found" % message['subject'])
if show_body: if show_body:
for m in message.get_payload(): if message.is_multipart():
if m.get_content_type() == 'text/plain': for part in message.walk():
print("Body:\n%s" % m.get_payload(decode=True).decode('utf-8')) ctype = part.get_content_type()
if ctype == "text/plain":
body = cast(bytes, part.get_payload(decode=True)).decode()
print(f"Body:\n{body}")
else:
print(f"Body with content type {ctype} not printed")
else:
body = cast(bytes, message.get_payload(decode=True)).decode()
print(f"Body:\n{body}")
break break
if message is None: if message is None:
@ -164,7 +174,7 @@ def send_and_read(args):
def read(args): def read(args):
_read_mail(imap_host=args.imap_host, _read_mail(imap_host=args.imap_host,
imap_port=args.imap_port, imap_port=args.imap_port,
to_addr=args.imap_username, imap_username=args.imap_username,
to_pwd=args.imap_password, to_pwd=args.imap_password,
subject=args.subject, subject=args.subject,
ignore_dkim_spf=args.ignore_dkim_spf, ignore_dkim_spf=args.ignore_dkim_spf,