1

I am writing a python script to fetch mail attachments through Graph API.

In the Graph Explorer, I can perfectly download file attachments by manually pressing the download button after calling:

https://graph.microsoft.com/v1.0/me/messages/{message-id}/attachments/{attachment-id}/$value

However, when trying to make the same request in my Python script, all I get returned is 'Response [200]' (so the request works, but the file is not reachable).

enter image description here

I try to make the request like this:

def get_mails_json():
  requestHeaders = {'Authorization': 'Bearer ' +result["access_token"],'Content-Type': 'application/json'}
  queryResults = msgraph_request(graphURI + "/v1.0/me/messages?$filter=isRead ne true",requestHeaders)

  return json.dumps(queryResults)

try:
    data = json.loads(mails)
    values = data['value']
    for i in values:
        mail_id = i['id']
        mail_subj = i['subject']            
        if i['hasAttachments'] != False:               
            attachments = o365.get_attachments(mail_id)
            attachments = json.loads(attachments)
            attachments = attachments['value']
            for i in attachments:                   
                details = o365.get_attachment_details(mail_id,i["id"])
except Exception as e:  
    print(e)


def get_attachment_details(mail,attachment):
requestHeaders = {'Authorization': 'Bearer ' + result["access_token"],'Content-Type': 'application/json'}
queryResults = msgraph_request(graphURI + "/v1.0/me/messages/"+mail+"/attachments/"+attachment+'/$value',requestHeaders)

return json.dumps(queryResults)

Is there a way for me to download the file to AT ALL through my python script ?

lvb
  • 41
  • 3
  • can you share the entire error message? – joshmeranda Nov 30 '21 at 15:33
  • This error message is a hint that you have tried to use `json.loads` on an empty string. Could you control what is `mails`? – Serge Ballesta Nov 30 '21 at 15:34
  • @joshmeranda I have updated my post - I no longer get an error as the request now succeeds, but I still have no way to download the file I want to. – lvb Nov 30 '21 at 15:51
  • @SergeBallesta I have updated my post - I have added the function I use to get the mails. I also no longer get an error, but a 200 response code. So the request succeeds, but I still cannot download the file. – lvb Nov 30 '21 at 15:52

1 Answers1

0

I found a simple solution to downloading a file through a python script!

I used chip's answer, found on this thread: thread containing chip's answer

I make the request for the attachment like so:

def get_attachment_details(mail,attachment):
requestHeaders = {'Authorization': 'Bearer ' + result["access_token"],'Content-Type': 'application/file'}
resource= graphURI + "/v1.0/me/messages/"+mail+"/attachments/"+attachment+'/$value'
payload = {}
results = requests.request("GET", resource,headers=requestHeaders,data=payload, allow_redirects=False)

return results.content

This gets me the encoded bytes of the file, which I then decode and write to a file like so:

for i in attachments:      
      details = o365.get_attachment_details(mail_id,i["id"])
      toread = io.BytesIO()
      toread.write(details)
      with open(i['name'], 'wb') as f:
         f.write(toread.getbuffer())
lvb
  • 41
  • 3