我在通过python的rest模块发送文件时遇到了一些问题。我可以发送没有附件的电子邮件,但只要我尝试添加一个files参数,调用失败,我得到一个415错误。在
我浏览了一下这个网站,发现这可能是因为我在构建数据数组时没有发送文件的内容类型,所以修改了它来查询mimetypes的内容类型;仍然是415。在
{还做了一些修改。在
错误消息显示:
“找不到与响应的内容类型匹配的受支持的MIME类型。没有支持的类型“”
然后列出一组json类型,例如:“'application/json;odata.metadata=最小;odata.streaming=真;IEEE754Compatible=错误“
然后说:
“匹配内容类型'multipart/form data;boundary=0e5485079df745cf0d0777a88aeb8fd'”
当然,这让我觉得我仍然没有正确地处理内容类型。在
有人能看出我的代码哪里出错了吗?在
谢谢!在
函数如下: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)