Chris Mellor
Chris Mellor

Reputation: 229

No attachments when reading messages (cannot save attachments)

I'm accessing an MS O365 Mail account using python and O365 libraries and can not access/save the file attachments for messages

I've done this using normal IMAP etc but now, because we have to user oauth2 and all that - I have to access the mailbox either through MS-Graph or some other way.

I went for the python-O365 libraries that allow me to do what I need.

I can get the folders and messages (names, bodies etc) but when I try to use the message.attachments method - I get the message that the number of attachments is unknown.

I know that there are two XLSX attachments for this message as I sent it myself and also I can verify that I'm reading the correct message because I can read the body of it.

I've searched for examples of saving attachments (using the O365 libs) but they don't address the problem (they iterate over the attachments collection - but I don't have any attachments).

I have read that attachments are stored separately from messages and that these need to be fetched separately but somehow this seems wrong?

The below code illustrates the problem...

for message in inbox.get_messages(5):
    print(message.subject)
    if message.subject == 'test':
        print('here')
        for att in message.attachments:
            print('also here')
            print(att.attachment_name)
            print(att.attachment_type)
            att.save()

From the above I get the text 'here' printed - so I know the correct message is being used. I don't get the text 'also here' which I should get as there are two files in the message.

So - any ideas how I can get my attachments saved?

Upvotes: 6

Views: 2396

Answers (1)

Chris Mellor
Chris Mellor

Reputation: 229

It just shows what a little time, an early morning and some good coffee can bring...

I found the answer. it was buried in the issues tracker for the O365 lib on github.

The following code works as it should:

for message in inbox.get_messages(limit=10, download_attachments=True):
    if message.subject == 'test with file':
        print('here')
        if message.has_attachments:
            print('also here')
            print(message.attachments)
            for att in message.attachments:
                print(att)
                att.save()

Compare that to the original code and you will see that I need to instruct get_messages to download_attachments=True and also the mechanism for accessing the attachments has changed.

Anyways - it's now working:)

Upvotes: 11

Related Questions