简体   繁体   中英

Parsing e-mail only with imap in python

conn = imaplib.IMAP4_SSL("imap.gmail.com", 993)
conn.login("login", "pass")
conn.select()
typ, data = conn.search(None, 'ALL')
z = open("email.txt", "a")

for num in data[0].split():
    typ, msg_data = conn.fetch(num, '(BODY[HEADER.FIELDS (SUBJECT FROM)])')
    for response_part in msg_data:
        if isinstance(response_part, tuple):
            msg = email.message_from_string(response_part[1])
            subject = msg['from']
            z.write("%s\n" % subject) 
            print(subject)

    typ, response = conn.store(num, '+FLAGS', r'(\Seen)')
finally:
try:
    conn.close()
except:
    pass
conn.logout()

I want the FROM: section from header only. Not full name also. I am now getting data returned as "First name LAst NAME" email@email.com the way I want the data is email@email.com

What you want is the envelope data item, not body.peek[header.fields (...)] . When you ask for envelope , the server does mucho parsing and gives you From, Subject and a few more. In the case of From you get a list of tuples, each of which may look like this: ("Google Play" NIL "googleplay-noreply" "google.com"). The first is the name you don't care about, the second is of historical interest only, and the third and fourth are what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM