首页 > 解决方案 > Python Post 请求 - 通过 Outlook API 发送文件时出现 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;边界=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)

标签: pythonrequesthttp-status-code-415

解决方案


我想通了!查看了 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)

推荐阅读