【发布时间】: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