python - Print only specific part of email -
i have code (below) shows me emails in email account. shows whole email, including metadata (which dont want). there way print to, from, subject , message only? in python well. thanks.
code:
import getpass, imaplib import os email = raw_input('email: ') password = getpass.getpass() m = imaplib.imap4_ssl("imap.gmail.com", 993) print('logging in ' + email + '...') m.login(email, password) m.select() typ, data = m.search(none, 'all') num in data[0].split(): typ, data = m.fetch(num, '(rfc822)') print ('message %s\n%s\n' % (num, data[0][1])) m.close() m.logout()
you can use email.parser.parser()
standard module parse mail , headers
from __future__ import print_function import imaplib import getpass import os email.parser import parser email = raw_input('email: ') password = getpass.getpass() print('logging in as', email, '...') m = imaplib.imap4_ssl("imap.gmail.com", 993) m.login(email, password) m.select() typ, data = m.search(none, 'all') num in data[0].split(): typ, data = m.fetch(num, '(rfc822)') #print ('message %s\n%s\n' % (num, data[0][1])) header = parser().parsestr(data[0][1]) print('from:', header['from']) print('to:', header['to']) print('subject:', header['subject']) print('body:') part in header.get_payload(): print(part.as_string()[:150], '.....') #break # test first message m.close() m.logout()
Comments
Post a Comment