R
R
Roqvie2019-04-22 23:46:35
Python
Roqvie, 2019-04-22 23:46:35

How to download files from mail attachments?

The code:

from imap_tools import MailBox
import email

mailbox = MailBox(host = 'imap.yandex.com', port = '993', ssl=True)
mailbox.login('[email protected]', 'PASSWORD')

for message in mailbox.fetch():
    print(message.from_values['full'])
    mail = message.obj
    if mail.is_multipart():
        for part in mail.walk():
            content_type = part.get_content_type()
            filename = part.get_filename()
            if filename:
                with open(part.get_filename(), 'wb') as new_file:
                    new_file.write(part.get_payload(decode = True))

Now the program can only download images.
I wish it could also download docx, pdf,
but so far it gives an error:
Traceback (most recent call last):
File "C:\Users\Admin\Desktop\yandexmailapi-master\mai -bot\index.py", line 18, in
with open(part.get_filename(), 'wb') as new_file:
OSError: [Errno 22] Invalid argument: '=?UTF-8?B?0LTQvtC60LvQsNC00JjRgdGC0L7RgNC40Y8=?= \r\n\t=?UTF-8?B?LmRvY3g=?='

Answer the question

In order to leave comments, you need to log in

3 answer(s)
L
Lamroy95, 2019-05-08
@Roqvie

Still, I had to register))
I did it like this:

h=email.header.make_header(email.header.decode_header(filename))
with open(str(h), 'wb') as new_file:
        new_file.write(part.get_payload(decode=True))

pdf is loaded fine, but doc (not docx) krakozyabra. If you find a solution, please reply here.
upd: docx is also downloaded and opens fine

D
Dimonchik, 2019-04-27
@dimonchik2013

did you manage to fix it? it is clear that the error is in fs and not in the mail?

U
uasha, 2019-05-08
@uasha

for part in msg.walk():
                content_type = part.get_content_type()
                filename = part.get_filename()
                if filename:
                    # Нам плохого не надо, в письме может быть всякое барахло
                    with open(part.get_filename(), 'w') as new_file:
                        f.write(str(part.get_payload(decode=True), encoding='utf-8'))
            f.close
<b></b>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question