MS Graph发邮件Python代码:嵌套JSON传递值引号去除问题
问题分析与解决
你的问题出在ccRecipients字段的赋值逻辑上:你已经通过列表推导式生成了符合MS Graph要求的cc_user_labels列表(每个元素都是正确的嵌套字典结构),但错误地用', '.join(map(str, ...))把这个列表转换成了字符串,还手动替换引号,这直接破坏了JSON的嵌套结构,导致格式错误。
修正后的代码
to_user_email = 'hello.world@test.com' cc_user_emails = ['hello.usa@scripps.com', 'hello.dc@scripps.com'] subject = 'hey' message = 'it looks like i cant remove quotes from this' # 这一步生成的结构完全符合要求,无需额外处理 cc_user_labels = [{"emailAddress":{"address": i}} for i in cc_user_emails] email_msg = { "message": { "subject": subject, "body": { "contentType": "Text", "content": message }, "toRecipients": [ { "emailAddress": { "address": to_user_email } } ], # 直接将cc_user_labels赋值给ccRecipients,它本身就是正确的列表结构 "ccRecipients": cc_user_labels }, "saveToSentItems": "true" }
关键修改点
- 移除了
ccRecipients中的字符串拼接和引号替换操作,直接使用已经生成好的cc_user_labels列表。 - 简化了
subject、content等字段的赋值,无需用f-string包裹变量(仅当需要格式化时才需使用)。
修正后的JSON结构(示例)
生成的email_msg会是标准的嵌套JSON格式,完全符合MS Graph的接口要求:
{ "message": { "subject": "hey", "body": { "contentType": "Text", "content": "it looks like i cant remove quotes from this" }, "toRecipients": [ { "emailAddress": { "address": "hello.world@test.com" } } ], "ccRecipients": [ { "emailAddress": { "address": "hello.usa@scripps.com" } }, { "emailAddress": { "address": "hello.dc@scripps.com" } } ] }, "saveToSentItems": "true" }
内容的提问来源于stack exchange,提问作者zabada
相关产品推荐
相关产品推荐

