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

使用应用ID与密钥连接后通过PowerShell处理O365邮箱邮件咨询

实现思路与完整方案

前置要求

  • 确认Azure AD注册应用已配置应用程序权限类型的Mail.ReadWrite权限,且已由管理员完成同意授权
  • 本地安装Microsoft Graph邮件相关PowerShell模块:
Install-Module Microsoft.Graph.Mail -Scope CurrentUser -Force

核心实现步骤

  1. 连接Microsoft Graph
    兼容你现有凭证获取逻辑,直接用已生成的凭证完成Graph连接即可:
# 你的原有凭证生成逻辑
$ClientID = "my-client-id"
$DirectoryID = "my-directory-id"
$ClientSecret = "my-client-secret"
$Credential = ConvertTo-GraphCredential -ClientID $ClientID -ClientSecret $ClientSecret -DirectoryID $DirectoryID
# 连接Graph
Connect-MgGraph -AccessToken $Credential.GetAccessToken()
# 配置目标邮箱UPN、本地存储路径、目标子文件夹名
$targetUPN = "myemailaccount@mycompany.com"
$localSavePath = "C:\MailAttachments"
$processedFolderName = "已处理邮件"
# 本地路径不存在则创建
if (-not (Test-Path $localSavePath)) {
    New-Item -ItemType Directory -Path $localSavePath | Out-Null
}
  1. 筛选收件箱中符合主题要求的邮件
# 按主题筛选,此处示例筛选主题包含「月度报表」的邮件,可根据需求调整筛选逻辑
$filterCondition = "parentFolderId eq 'Inbox' and contains(subject, '月度报表')"
$targetMails = Get-MgUserMessage -UserId $targetUPN -Filter $filterCondition -All:$true
  1. 遍历邮件下载附件并移动已处理邮件
foreach ($mail in $targetMails) {
    # 获取当前邮件所有附件
    $attachments = Get-MgUserMessageAttachment -UserId $targetUPN -MessageId $mail.Id
    foreach ($att in $attachments) {
        # 仅处理文件类型附件,跳过内嵌资源等其他类型
        if ($att.ODataType -eq '#microsoft.graph.fileAttachment') {
            $saveFilePath = Join-Path $localSavePath $att.Name
            # 将附件二进制内容写入本地文件
            [System.IO.File]::WriteAllBytes($saveFilePath, $att.ContentBytes)
        }
    }
    # 处理完成后移动邮件到目标子文件夹
    # 先获取目标子文件夹ID
    $targetFolder = Get-MgUserMailFolder -UserId $targetUPN -Filter "displayName eq '$processedFolderName'"
    if ($targetFolder) {
        Move-MgUserMessage -UserId $targetUPN -MessageId $mail.Id -DestinationId $targetFolder.Id
    }
}

注意事项

  • 主题筛选支持eq(完全匹配)、startsWith(开头匹配)、contains(包含匹配)等操作符,可根据需求调整筛选条件
  • 如处理超过1000封的大量邮件,可添加分页参数避免接口调用限制
  • 大体积附件(>4MB)建议使用Graph的分段下载接口,避免内存溢出

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 08:27:03