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

如何通过AZ CLI获取Outlook邮件?解决Get-MgAuthenticationToken未识别错误

解决获取Outlook邮件的PowerShell报错及实现方法

错误原因

你用的Get-AzOutlookMessage并不是AZ CLI(Az模块)里的有效命令,Az模块主要用来管理Azure云资源,没法直接访问Outlook邮件。报错里的Get-MgAuthenticationToken属于Microsoft Graph PowerShell模块,这才是访问Outlook(Exchange Online)邮件的正确工具。

解决方案:使用Microsoft Graph PowerShell模块

1. 安装必要模块

打开管理员权限的PowerShell,执行以下命令安装模块:

# 安装Microsoft Graph模块
Install-Module -Name Microsoft.Graph -Force -AllowClobber

# 可选:安装ImportExcel模块,导出Excel更稳定(替代COM对象)
Install-Module -Name ImportExcel -Force -AllowClobber

2. 授权访问权限

连接到Microsoft Graph并申请邮件读取权限:

Connect-MgGraph -Scopes "Mail.Read"

执行后会弹出浏览器,用目标邮箱的账号登录完成授权。

3. 获取邮件并导出到Excel

替换你原来的代码,用以下脚本实现:

$userEmail = "user@example.com"
$folderName = "Inbox"
$outputFile = "emails.xlsx"

# 先获取收件箱的文件夹ID
$mailFolder = Get-MgUserMailFolder -UserId $userEmail -Filter "displayName eq '$folderName'"
if (-not $mailFolder) {
    Write-Error "找不到名为$folderName的邮件文件夹"
    exit
}

# 获取收件箱中的邮件(Top参数可调整获取的邮件数量)
$outlookMessages = Get-MgUserMailFolderMessage -UserId $userEmail -MailFolderId $mailFolder.Id -Top 100 | 
    Select-Object Subject, From, ReceivedDateTime, BodyPreview

# 推荐:用ImportExcel模块导出(无需本地安装Excel,格式更规整)
$outlookMessages | Export-Excel -Path $outputFile -AutoSize -TableName "Emails"

# 备选:用原COM对象方式导出(需本地安装Excel)
# $excel = New-Object -ComObject Excel.Application
# $excel.Visible = $false
# $workbook = $excel.Workbooks.Add()
# $sheet = $workbook.Worksheets.Item(1)
# # 写入表头
# $headers = $outlookMessages[0].PSObject.Properties.Name
# for ($i=0; $i -lt $headers.Count; $i++) {
#     $sheet.Cells(1, $i+1) = $headers[$i]
# }
# # 写入邮件内容
# for ($row=0; $row -lt $outlookMessages.Count; $row++) {
#     for ($col=0; $col -lt $headers.Count; $col++) {
#         $sheet.Cells($row+2, $col+1) = $outlookMessages[$row].($headers[$col])
#     }
# }
# $workbook.SaveAs($outputFile)
# $excel.Quit()
# [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null

更简便的替代方案

如果只是导出邮件,也可以用Exchange Online PowerShell模块:

  1. 安装模块:
Install-Module -Name ExchangeOnlineManagement -Force -AllowClobber
  1. 连接并导出:
Connect-ExchangeOnline -UserPrincipalName $userEmail
$outlookMessages = Get-MailboxFolderStatistics -Identity $userEmail -FolderScope Inbox | 
    Get-Message -ResultSize 100 | Select-Object Subject, From, ReceivedTime, BodyPreview
$outlookMessages | Export-Excel -Path $outputFile -AutoSize

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 11:00:00