This is a minimal example of fetching emails from IMAP server using Python imaplib package. (You can check a similar source code from the official documentation.)
import imaplib
import email
HOST="MY_AWOSOME_IMAP_SERVER"
USER="me@awsome.domain"
PASS="awesome password"
with imaplib.IMAP4_SSL(host=HOST, port=993) as imap:
# Log in
print("Logging in...")
resp_code, resp = imap.login(USER, PASS)
# Fetch the last two emails
resp_code, mail_ids = imap.search(None, "ALL")
print(f"Response code: {resp_code}")
for mail_id in mail_ids[0].decode().split()[-2:]:
print(f"-> Mail {mail_id}")
resp_code, mail_data = imap.fetch(mail_id, '(RFC822)')
msg = email.message_from_bytes(mail_data[0][1])
print(f"From : {msg.get('From')}")
print(f"To : {msg.get('To')}")
print(f"Date : {msg.get('Date')}")
print(f"Subject: {msg.get('Subject')}")
print()
imap.close()
- This code works well when I tested it for many email servers including gmail.com.
- But it doesn't work when I tested for my client's email server.
The engineer from my client's email provider suggests to change the second parameter in the fetch
command.
resp_code, mail_data = imap.fetch(mail_id, 'UID RFC822.SIZE FLAGS BODY.PEEK[HEADER.FIELDS (From To Cc Bcc Subject Date Message-ID Priority X-Priority References Newsgroups In-Reply-To Content-Type Reply-To)]')
If I replace '(RFC822)'
with a lengthy text 'UID RFC822.SIZE FLAGS BODY.PEEK[HEADER.FIELDS (From To Cc Bcc Subject Date Message-ID Priority X-Priority References Newsgroups In-Reply-To Content-Type Reply-To)]'
, then I have this strange behaviour.
- Now the code works for my client's email server.
- But it doesn't work for other email servers including gmail.com
What does this lengthy parameter 'UID RFC822.SIZE FLAGS BODY.PEEK[HEADER.FIELDS (From To Cc Bcc Subject Date Message-ID Priority X-Priority References Newsgroups In-Reply-To Content-Type Reply-To)]'
do? A quick SO search shows one question containing this parameter, but I cannot understand why this parameter works for my client but fails for other emails servers.
Can anyone explain what this is about?