You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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"
}

关键修改点

  1. 移除了ccRecipients中的字符串拼接和引号替换操作,直接使用已经生成好的cc_user_labels列表。
  2. 简化了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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 13:06:17