Last active
April 7, 2023 15:54
-
-
Save strayge/f619cacb972d956ddbe1472d882821fe to your computer and use it in GitHub Desktop.
email parse pop3 python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import poplib | |
import email | |
from base64 import b64decode | |
pop3_server = 'pop.gmail.com' | |
pop3_port = '995' | |
username = 'XXXXXXXXXX@gmail.com' | |
password = 'XXXXXXXXXXXXXX' | |
M = poplib.POP3_SSL(pop3_server, pop3_port) | |
M.user(username) | |
M.pass_(password) | |
numMessages = len(M.list()[1]) | |
def decode_header(header): | |
decoded_bytes, charset = email.header.decode_header(header)[0] | |
if charset is None: | |
return str(decoded_bytes) | |
else: | |
return decoded_bytes.decode(charset) | |
for i in range(numMessages): | |
raw_email = b"\n".join(M.retr(i+1)[1]) | |
parsed_email = email.message_from_bytes(raw_email) | |
print('=========== email #%i ============' % i) | |
print('From:', parsed_email['From']) | |
print('To:', parsed_email['To']) | |
print('Date:', parsed_email['Date']) | |
print('Subject:', decode_header(parsed_email['Subject'])) | |
for part in parsed_email.walk(): | |
if part.is_multipart(): | |
# maybe need also parse all subparts | |
continue | |
elif part.get_content_maintype() == 'text': | |
text = part.get_payload(decode=True).decode(part.get_content_charset()) | |
print('Text:\n', text) | |
elif part.get_content_maintype() == 'application' and part.get_content_disposition() == 'attachment': | |
name = decode_header(part.get_filename()) | |
body = part.get_payload(decode=True) | |
size = len(body) | |
print('Attachment: "{}", size: {} bytes, starts with: "{}"'.format(name, size, body[:50])) | |
else: | |
print('Unknown part:', part.get_content_type()) | |
print('======== email #%i ended =========' % i) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment