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

Python Post Request - Getting 415 Error When Sending Files via Outlook API

我在通过 python 的 rest 模块发送文件时遇到了一些问题。我可以发送没有附件的电子邮件,但只要我尝试添加文件参数,调用就会失败,我会收到 415 错误。

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

此线程:python requests file upload 进行了更多编辑,但仍为 415。

错误消息说:

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

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

然后说:

"matches the content type '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)

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