Python发布请求-通过Outlook API发送文件时出现415错误

时间:2019-04-12 09:05:39

标签: python request multiple-files http-status-code-415

我在通过python的rest模块发送文件时遇到了一些麻烦。我可以发送不带附件的电子邮件很好,但是一旦尝试添加文件参数,调用就会失败,并出现415错误。

我浏览了该网站,发现可能是因为在构建数据数组时我没有发送文件的内容类型,因此将其更改为使用mimetypes查询内容类型。还是415。

此线程:python requests file upload进行了多次其他修改,但仍为415。

错误消息显示:

“找不到与响应的内容类型匹配的受支持的MIME类型。没有受支持的类型”

然后列出了一堆json类型,例如:“'application / json; odata.metadata = minimal; odata.streaming = true; IEEE754Compatible = false”

然后说:

“匹配内容类型'multipart / form-data; boundary = 0e5485079df745cf0d07777a88aeb8fd'”

当然,这让我觉得我在某处仍然无法正确处理内容类型。

任何人都可以在代码中看到我要去哪里吗?

谢谢!

功能如下:


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 个答案:

答案 0 :(得分:0)

我知道了!看了一下Outlook API文档,意识到我应该在消息Json中而不是request.post函数中以编码列表的形式添加附件。这是我的工作示例:

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)