Reading mail getting [<email.message.Message object at 0x02209970>, ...
MRAB
python at mrabarnett.plus.com
Thu Nov 14 16:06:09 EST 2019
On 2019-11-14 19:43, Abdur-Rahmaan Janhangeer wrote:
> Greetings,
>
> Using this code to read mail. I'm printing to file only mails sent by some
> people. For some mails i get the body as the below instead of actual text:
>
> [<email.message.Message object at 0x02209970>, <email.message.Message
> object at 0x021ECB30>]
>
> instead of the actual mail body.
>
> Here is the code:
>
> #
> #
> import imaplib
> import email
> import time
>
> my_senders = ['you at x.com ', 'you at y.com', 'you at z.com']
> my_mail_count = 1
> open('data.txt', 'w+')
> def read_email_from_gmail():
> global my_mail_count, my_senders
>
> mail = imaplib.IMAP4_SSL('imap.gmail.com')
> mail.login('mymail at gmail.com','password')
> mail.select('inbox')
>
> result, data = mail.search(None, 'ALL')
> mail_ids = data[0]
>
> id_list = mail_ids.split()
> first_email_id = int(id_list[0])
> latest_email_id = int(id_list[-1])
>
> for i in range(latest_email_id,first_email_id, -1):
> #pypi # need str(i)
> result, data = mail.fetch(str(i), '(RFC822)' )
>
> for response_part in data:
> if isinstance(response_part, tuple):
> # from_bytes, not from_string
> msg = email.message_from_bytes(response_part[1])
>
> email_subject = msg['subject']
> email_from = msg['from']
> print ('{} {}'.format(my_mail_count, email_subject))
> print(' {}'.format(email_from))
> my_mail_count += 1
>
> #email_body = msg.get_payload(decode=True)
>
> for m in my_senders:
> if m in email_from:
> if msg.is_multipart():
> for part in msg.get_payload():
> print(msg.get_payload(),
> file=open('data.txt', 'a'))
> if isinstance(msg.get_payload(), list):
> print(dir(msg.get_payload()[0]))
> else:
> print(msg.get_payload(), file=open('data.txt',
> 'a'))
> if isinstance(msg.get_payload(), list):
> print(dir(msg.get_payload()[0]))
>
> read_email_from_gmail()
> #
> #
>
> Any idea?
>
The payload is sometimes split into parts that are encoded. Do something
like this:
from email.header import decode_header
def decode_payload(header, default_encoding='utf-8'):
parts = []
for data, encoding in decode_header(header):
if isinstance(data, str):
parts.append(data)
else:
parts.append(data.decode(encoding or default_encoding))
return ' '.join(parts)
More information about the Python-list
mailing list