pythonfetchimaplibapple-mail

Does imaplib works to download a pdf inside a mail from AppleMail?


I am trying to download the pdf from a mail received on an Apple account xy@me.com.

I have already managed to do it from a gmail account with no trouble but the result from imaplib.fetch seems to be empty using RFC822 when I apply it to a "@me.com" account, I get:

b'34878 ()'

When I use BODY instead, I get infos about the content of the body but I don't know how to access it. I cannot check if it is a multipart email, use .walk or .get("Content-Disposition") nor .get_payload(decode=True)

import imaplib
import email

username = 'username'
password = 'password'
hostname = 'imap.mail.me.com'
port = '993'
expeditor= 'expeditor'
subj = 'subject of the mail'
since="01-Oct-2022"

# Connect to the server
connection = imaplib.IMAP4_SSL(hostname,port)
# Login to my account
connection.login(username, password)
status, messages = connection.select("INBOX")
# total number of emails
messages_number = int(messages[0])
print(f'{messages_number=}')
# Search for specific emails
typ_search, msg_ids_search = connection.search(None, 'SINCE', "{since}",'FROM', f'"{expeditor}"', 'SUBJECT', f'"{subj}"')
print(f'{msg_ids_search[0]=}')
# Select only the first message to test
msg_to_test=emails_ids=[elt.decode() for elt in msg_ids_search[0].split()][0]
print(f'{msg_to_test=}')
# Fetch the message to test
res, msg = connection.fetch(msg_to_test, ("BODY"))
print(f'{msg=}')

This is what I get:

messages_number=35780
msg_ids_search[0]=b'34878 34879'
msg_to_test='34878'
msg=[b'34878 (BODY ((("text" "html" ("CHARSET" "utf-8") NIL NIL "quoted-printable" 4128 74)("image" "jpeg" ("NAME" "img1") "<img1>" NIL "base64" 129910) "related")("application" "pdf" ("NAME" "0304217.pdf") NIL NIL "base64" 433256) "mixed"))']

How can I access the “application” part to download “0304217.pdf”?

Thank you so much for your help!


Solution

  • As I didn't get any answer to my question, I have been searching for a solution for the past few days. I managed to do it by using MailBox instead of imaplib.