Python调用Microsoft Graph发送多收件人邮件时报错
解决Microsoft Graph API发送多收件人邮件的RequestBodyRead错误
问题原因
报错明确指出'Email Address'不是microsoft.graph.recipient的合法属性——你用了带空格的键名,但Microsoft Graph API要求的正确属性名是**EmailAddress**(无空格)。你的recipient_list生成逻辑用了错误的键名,导致API无法解析请求体。
修复步骤
- 核心修正:收件人格式
把生成recipient_list的代码中'Email Address'改成'EmailAddress',这是解决报错的关键。 - 顺带修复其他潜在问题
- 附件部分的
@odata. type有多余空格,需改为@odata.type - 变量名拼写错误:
mine_type改为mime_type,避免未定义报错
- 附件部分的
修正后的完整代码
def send_email(token, subject, recipients=None, body= None, content_type='HTML', attachments=None): try: print("inside send mail") userId = str(EmailID) graph_url = f'https://graph.microsoft.com/v1.0/users/{userId}/sendMail' # 校验必填参数 if not all([token, subject, recipients]): raise ValueError('sendmail(): required arguments missing') # 生成符合要求的收件人列表(已修正键名) recipient_list = [{'EmailAddress': {'Address': address}} for address in recipients] print(recipient_list) # 处理附件 attached_files = [] if attachments: for filename in attachments: b64_content = base64.b64encode(open(filename, 'rb').read()) mime_type = mimetypes.guess_type(filename)[0] mime_type = mime_type or '' attached_files.append( {'@odata.type': '#microsoft.graph.fileAttachment', 'ContentBytes': b64_content.decode('utf-8'), 'ContentType': mime_type, 'Name': filename}) email_msg = {'Message': {'Subject': subject, 'Body': {'ContentType': content_type, 'Content': body}, 'ToRecipients': recipient_list, 'Attachments': attached_files}, 'SaveToSentItems': 'true'} res = requests.post( graph_url, headers={ 'Authorization': 'Bearer {0}'.format(token), 'Content-Type': 'application/json' }, data=json.dumps(email_msg)) print(res.json()) except Exception as e: print(e)
验证效果
修正后recipient_list的格式会变为:
[{'EmailAddress': {'Address': 'Heer@company.com'}}, {'EmailAddress': {'Address': 'harry@company.com'}}]
该格式完全符合Microsoft Graph API对recipient类型的定义,API将能正确解析收件人信息,不再触发RequestBodyRead错误。
内容的提问来源于stack exchange,提问作者ask questions
相关产品推荐
相关产品推荐

