0

I've been having some trouble sending files via python's rest module. I can send emails without attachments just fine but as soon as I try and add a files parameter, the call fails and I get a 415 error.

I've looked through the site and found out it was maybe because I wasn't sending the content type of the files when building that array of data so altered it to query the content type with mimetypes; still 415.

This thread: python requests file upload made a couple of more edits but still 415.

The error message says:

"A supported MIME type could not be found that matches the content type of the response. None of the supported type(s)"

Then lists a bunch of json types e.g: "'application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false"

then says:

"matches the content type 'multipart/form-data; boundary=0e5485079df745cf0d07777a88aeb8fd'"

Which of course makes me think I'm still not handling the content type correctly somewhere.

Can anyone see where I'm going wrong in my code?

Thanks!

Here's the function:


def send_email(access_token):

    import requests
    import json
    import pandas as pd
    import mimetypes

    url = "https://outlook.office.com/api/v2.0/me/sendmail"

    headers = {
        'Authorization': 'Bearer '+access_token,
    }

    data = {}
    data['Message'] = {
        'Subject': "Test",
        'Body': {
            'ContentType': 'Text',
            'Content': 'This is a test'
        },
        'ToRecipients': [
            {
                'EmailAddress':{
                'Address': 'MY TEST EMAIL ADDRESS'
                }
            }
        ]
    }
    data['SaveToSentItems'] = "true"

    json_data = json.dumps(data)
    #need to convert the above json_data to dict, otherwise it won't work
    json_data = json.loads(json_data)

    ###ATTACHMENT WORK
    file_list = ['test_files/test.xlsx', 'test_files/test.docx']

    files = {}
    pos = 1
    for file in file_list:
        x = file.split('/') #seperate file name from file path

        files['file'+str(pos)] = ( #give the file a unique name
        x[1], #actual filename
        open(file,'rb'), #open the file
        mimetypes.MimeTypes().guess_type(file)[0] #add in the contents type
        )

        pos += 1 #increase the naming iteration

    #print(files)

    r = requests.post(url, headers=headers, json=json_data, files=files)

    print("")
    print(r)
    print("")
    print(r.text)

1 Answers1

0

I've figured it out! Took a look at the outlook API documentation and realised I should be adding attachments as encoded lists within the message Json, not within the request.post function. Here's my working example:

import requests
import json
import pandas as pd
import mimetypes
import base64

url = "https://outlook.office.com/api/v2.0/me/sendmail"

headers = {
    'Authorization': 'Bearer '+access_token,
}


Attachments = []
file_list = ['test_files/image.png', 'test_files/test.xlsx']

for file in file_list:

    x = file.split('/') #file the file path so we can get it's na,e
    filename = x[1] #get the filename
    content = open(file,'rb') #load the content

    #encode the file into bytes then turn those bytes into a string
    encoded_string = ''
    with open(file, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read())

    encoded_string = encoded_string.decode("utf-8")

    #append the file to the attachments list
    Attachments.append({
            "@odata.type": "#Microsoft.OutlookServices.FileAttachment",
            "Name": filename,   
            "ContentBytes": encoded_string        
    })


data = {}
data['Message'] = {
    'Subject': "Test",
    'Body': {
        'ContentType': 'Text',
        'Content': 'This is a test'
    },
    'ToRecipients': [
        {
            'EmailAddress':{
            'Address': 'EMAIL_ADDRESS'
            }
        }
    ],
    "Attachments": Attachments
}
data['SaveToSentItems'] = "true"

json_data = json.dumps(data)
json_data = json.loads(json_data)



r = requests.post(url, headers=headers, json=json_data)

print(r)