First I connect to my own mailbox using such code:
import email
import imaplib
imap_server = imaplib.IMAP4_SSL('imap.gmail.com', 993)
imap_server.login("myemail", "mypassword")
imap_server.select('inbox')
Then I get the last email on it in the way like:
_, data = imap_server.search(None, 'ALL')
id_list = data[0].split()
_, data = imap_server.fetch(id_list[-1], '(RFC822)')
rawmail = data[0][1]
prev_mail = email.message_from_bytes(rawmail)
And after that, I need to get sender email from prev_mail
variable.
I tried it myself a little bit, and figured out that prev_mail['From']
is usually sth like this: "John Snow" <johnsnow@gmail.com>
, so that means I can just grab the <*>
part and use it.
But the question is: will it always be like this so I could use my method? And are there any better ways to do this rather than mine?
EDIT:
There are multiple variants of From: headers. Python 3.8 has a good parser for this in the email.header module. But perhaps the Return-Path: header would actually be closer to what you really want? - tripleee
Thank you very much, tripleee, that's exactly what I needed!