How do I find out who sent me an email?

You need to create a function that will go to Google Mail and give me the mail from which I received the letters. I can't solve this problem, I tried a lot of things, nothing helped.

How can this be done?

import imaplib

login = str(self.login.get())
        password = str(self.password.get())
        mail1 = str(self.mail.get())
        mail = imaplib.IMAP4_SSL('imap.gmail.com')
        mail.login({login},{password})
        mail.select('inbox')

Here I use information input blocks, and in this function I use them.

Author: 0xdb, 2020-10-01

1 answers

Example:

import re
import imaplib
import email

mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('[email protected]','mypassword')

# сначала выбираем папку All Mail
folder = [re.sub(r'.*?("\[G[^"]*").*', r'\1', f.decode("utf-8"))  for f in mail.list()[1] if br"\All " in f][0]

mail.select(folder)

# поиск писем по отправителю
typ, data = mail.search(None, '(FROM "Paul")')

ID of the found emails

In [29]: data
Out[29]: [b'5828 6791 6956 7523 7840']

Reading and parsing one of the found emails:

typ, d = mail.fetch('5828', '(RFC822)')
msg = email.message_from_bytes(d[0][1])

Attributes msg:

In [34]: msg.keys()
Out[34]:
['Delivered-To',
 'Received',
 'X-Received',
 'Return-Path',
 'Received',
 'Received-SPF',
 'Authentication-Results',
 'Received',
 'DKIM-Signature',
 'X-Google-DKIM-Signature',
 'X-Gm-Message-State',
 'X-Received',
 'MIME-Version',
 'Received',
 'Received',
 'From',
 'Date',
 'Message-ID',
 'Subject',
 'To',
 'Content-Type']

Then you can view each of these attributes:

In [35]: print(msg["from"])
Paul ****** <paul.******@******.com>

 2
Author: MaxU, 2020-10-01 13:59:58