I'm trying to save email attachment from Google mail account.
AFAIK, it can be done 'walking' the message and getting its payload,
for part in message.walk():
# getting payload, saving attach etc.
but it does not work. See the whole example below:
def test_save_attach(self):
self.connection = poplib.POP3_SSL('pop.gmail.com', 995)
self.connection.set_debuglevel(1)
self.connection.user(USERNAME)
self.connection.pass_(PASS)
emails, total_bytes = self.connection.stat()
print("{0} emails in the inbox, {1} bytes total".format(emails, total_bytes))
# return in format: (response, ['mesg_num octets', ...], octets)
msg_list = self.connection.list()
print(msg_list)
# messages processing
for i in range(emails):
response = self.connection.retr(i+1)
# return in format: (response, ['line', ...], octets)
lines = response[1]
str_message = email.message_from_bytes(b''.join(lines))
print(str_message)
# save attach
for part in str_message.walk():
print(part.get_content_type())
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
filename = part.get_filename()
if not(filename): continue
fp = open(os.path.join(self.savedir, filename), 'wb')
fp.write(part.get_payload(decode=1))
fp.close
self.connection.quit()
Script output is:
*cmd* 'USER **********'
*cmd* 'PASS **********'
*cmd* 'STAT'
*stat* [b'+OK', b'1', b'5301']
1 emails in the inbox, 5301 bytes total
*cmd* 'LIST'
(b'+OK 1 messages (5301 bytes)', [b'1 5301'], 8)
*cmd* 'RETR 1'
[<message headers and body>]
text/plain
*cmd* 'QUIT'
As we can see, the only part of the message has 'text/plain' format and does not contain any attach information, although the message body defenitely contains it and it can be seen while debug output.