imalib cant get From: adresses

Bischoop Bischoop at vimart.net
Wed Jan 27 09:30:33 EST 2021


I don't have much experience with imaplib and for a few days can't
manage to get properly, I followed also some tutorial but also met few
problems.
What I want is to get email addresses from emails I do have in gmail
inbox. The code below gets them but then pops an error.
When I change the part "for i in range()" as in commented line it gets
just the last email.

Anybody familiar here with imaplib? 


import getpass, imaplib
import email
from email.header import decode_header

M = imaplib.IMAP4_SSL('imap.gmail.com')
M.login(u, p)
M.select()
status, messages = M.select("INBOX")
di={}

# number of top emails to fetch
N = 100

# total number of emails
messages = int(messages[0])

for i in range(messages, messages-N,-1):
#for i in range(messages, N):
    # fetch the email message by ID
    res, msg = M.fetch(str(i), "(RFC822)")
    for response in msg:
        if isinstance(response, tuple):
            # parse a bytes email into a message object
            msg = email.message_from_bytes(response[1])


            From, encoding = decode_header(msg.get("From"))[0]
            if isinstance(From, bytes):
                From = From.decode(encoding)
            print("From:", From)
            print(type(From))


            print("="*100)
            if '<'in From:
                s = From.index('<')
                d = From.index('>')
                q = From[s + 1:d]
                w = From[0:s - 1]
                if q in di.values():
                    pass
                else:
                    di[w] = q
            else:
                if q not in di.values():

                    b = sum(1 for key in di if key.startswith('Friend'))
                    di[f'Friend{b+1}']=From
# close the connection and logout
M.close()
M.logout()

print(di)
for i in di.keys():
    if 'Friend' in i:
        print(From,'\n',i,di[i])

b = sum(1 for key in di if key.startswith('Friend'))
print(b)

    raise self.error('%s command error: %s %s' % (name, typ, data))
imaplib.error: FETCH command error: BAD [b'Could not parse command']

Process finished with exit code 1



========================




More information about the Python-list mailing list