parsing email contents from poplib with email module (PYTHON)

只谈情不闲聊 提交于 2019-12-06 14:53:24

the answer turned out to be fairly easy

import getpass, poplib, email
Mailbox = poplib.POP3_SSL('pop.googlemail.com', '995')
Mailbox.user("email_here@gmail.com")
Mailbox.pass_('password_here')
numMessages = len(Mailbox.list()[1])
for i in range(numMessages):
    raw_email  = b"\n".join(Mailbox.retr(i+1)[1])
    parsed_email = email.message_from_bytes(raw_email)
    print(parsed_email.keys())

instead of joining raw_email with a space just join it by a \n and the email module can parse the fields correctly:

also an a awesome thing about using the email module is when you call email.message_from_bytes() the output returned is a dict

so you access the fields like this:

raw_email  = b"\n".join(Mailbox.retr(i+1)[1])
parsed_email = email.message_from_bytes(raw_email)
print(parsed_email["header"])

but what if the field doesn't exist?:

raw_email  = b"\n".join(Mailbox.retr(i+1)[1])
parsed_email = email.message_from_bytes(raw_email)
print(parsed_email["non-existent field"])

the above code will return None and not throw a KeyError

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!