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

使用Microsoft Graph SDK for Python发送邮件时SendMailPostRequestBody类缺失求助

解决msgraph模块无SendMailPostRequestBody类的问题

你遇到的问题是Microsoft Graph Python SDK版本差异导致的——参考的示例代码基于旧版SDK,新版SDK已简化邮件发送的调用逻辑,无需再使用SendMailPostRequestBody类,同时也能轻松实现带附件的邮件发送。

修正后的带附件邮件发送代码

from msgraph import GraphServiceClient
from msgraph.generated.models.message import Message
from msgraph.generated.models.item_body import ItemBody
from msgraph.generated.models.recipient import Recipient
from msgraph.generated.models.email_address import EmailAddress
from msgraph.generated.models.file_attachment import FileAttachment
from msgraph.generated.models.body_type import BodyType

# 初始化Graph客户端
graph_client = GraphServiceClient(credentials, scopes)

# 构建核心邮件内容
message = Message(
    subject="Meet for lunch?",
    body=ItemBody(
        content_type=BodyType.Text,
        content="The new cafeteria is open."
    ),
    to_recipients=[
        Recipient(
            email_address=EmailAddress(
                address="frannis@contoso.com"
            )
        )
    ],
    cc_recipients=[
        Recipient(
            email_address=EmailAddress(
                address="danas@contoso.com"
            )
        )
    ]
)

# 添加本地文件作为附件
with open("lunch_menu.pdf", "rb") as f:
    attachment_data = f.read()

file_attachment = FileAttachment(
    name="lunch_menu.pdf",
    content_type="application/pdf",
    content_bytes=attachment_data
)

# 将附件关联到邮件
message.attachments = [file_attachment]

# 直接传入参数发送邮件
await graph_client.me.send_mail.post(message=message, save_to_sent_items=False)

关键说明

  • 新版SDK中,send_mail.post()方法支持直接接收message和save_to_sent_items参数,无需封装到请求体类中。
  • 若需转发邮件,可直接从原邮件的attachments属性中获取附件对象,添加到新邮件的attachments列表即可,无需重新读取文件。
  • 附件类型除了FileAttachment,还可根据需求使用ItemAttachment(附加Outlook项)或ReferenceAttachment(附加云文件链接)。

内容的提问来源于stack exchange,提问作者user480840

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 20:44:53