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

如何用Kotlin+Microsoft Graph API V6替换V5代码实现邮件发送

解决方案:使用Microsoft Graph V6 Java SDK从指定发件人发送邮件

报错原因

你遇到的/me request is only valid with delegated authentication flow报错,是因为当前使用Client Secret应用权限认证,而/me接口仅支持**委托权限(用户登录)**场景。要实现从指定发件人发送邮件,需要直接指定用户ID或邮箱调用接口。

V6替代实现代码

替换你原来的graphClient.me().sendMail()调用,改用指定用户的方式发送,完整代码如下:

val clientId = ""
val tenantId = ""
val clientSecret = ""

val scopes = arrayOf("https://graph.microsoft.com/.default")

val credential = ClientSecretCredentialBuilder()
    .clientId(clientId)
    .tenantId(tenantId)
    .clientSecret(clientSecret)
    .build() ?: throw Exception("Failed to create credential")

val graphClient = GraphServiceClient(credential, *scopes)

// 准备邮件消息(这部分和你原代码一致)
val message = Message()
message.subject = "Meet for lunch?"
val body = ItemBody()
body.contentType = BodyType.Html
body.content = "The new cafeteria is open."
message.body = body

val toRecipients = LinkedList<Recipient>()
val toRecipient = Recipient()
val toEmailAddress = EmailAddress()
toEmailAddress.address = "frannis@contoso.com"
toRecipient.emailAddress = toEmailAddress
toRecipients.add(toRecipient)
message.toRecipients = toRecipients

val ccRecipients = LinkedList<Recipient>()
val ccRecipient = Recipient()
val ccEmailAddress = EmailAddress()
ccEmailAddress.address = "danas@contoso.com"
ccRecipient.emailAddress = ccEmailAddress
ccRecipients.add(ccRecipient)
message.ccRecipients = ccRecipients

// 创建SendMail请求体
val sendMailPostRequestBody = SendMailPostRequestBody()
sendMailPostRequestBody.message = message
sendMailPostRequestBody.saveToSentItems = true // 和V5一致,保存到已发送邮件

val emailSender = "sender365@contoso.com"

// V6核心发送逻辑(替代V5的users(it).sendMail部分)
emailSender?.let { sender ->
    graphClient.users()
        .byUserId(sender) // 指定发件人邮箱或用户ID
        .sendMail()
        .post(sendMailPostRequestBody)
}

关键注意事项

  • 权限配置:确保Azure AD应用已添加Mail.Send应用权限,并完成管理员同意。
  • 发件人合法性:指定的emailSender必须是当前租户内的有效用户邮箱,且应用有权限操作该用户的邮箱资源。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 21:26:16