【问题标题】:Python Post Request - Getting 415 Error When Sending Files via Outlook APIPython Post 请求 - 通过 Outlook API 发送文件时出现 415 错误
【发布时间】:2019-09-03 00:16:34
【问题描述】:

我在通过 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)

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-22
      • 2021-12-13
      相关资源
      最近更新 更多