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

使用PowerShell从Exchange Online邮箱特定文件夹下载附件

连接Exchange Online并下载指定文件夹附件的实现方案

方案一:Exchange Online PowerShell模块(运维/快速自动化首选)

适合批量操作,无需复杂开发,直接通过脚本完成需求。

1. 安装并连接模块

# 首次运行安装模块
Install-Module -Name ExchangeOnlineManagement -Force -AllowClobber

# 连接到Exchange Online(会弹出登录窗口)
Connect-ExchangeOnline -UserPrincipalName your-email@domain.com

2. 下载指定文件夹附件脚本

替换"收件箱/你的目标文件夹"和本地保存路径为实际值:

# 配置参数
$mailbox = "your-email@domain.com"
$targetFolderPath = "收件箱/你的目标文件夹"
$localSaveDir = "C:\ExchangeAttachments"

# 创建本地目录(不存在则新建)
if (-not (Test-Path $localSaveDir)) {
    New-Item -ItemType Directory -Path $localSaveDir | Out-Null
}

# 定位目标文件夹
$targetFolder = Get-MailboxFolderStatistics -Identity $mailbox | Where-Object { $_.FolderPath -eq $targetFolderPath }
if (-not $targetFolder) {
    Write-Error "未找到指定文件夹:$targetFolderPath"
    exit
}

# 遍历邮件并下载附件
$emails = Get-EXOMessage -Mailbox $mailbox -FolderId $targetFolder.FolderId -PageSize 1000
foreach ($email in $emails) {
    foreach ($attachment in $email.Attachments) {
        if ($attachment.Size -gt 0) { # 跳过空附件
            $savePath = Join-Path -Path $localSaveDir -ChildPath $attachment.Name
            $attachment | Get-EXOAttachmentContent -SaveToFile $savePath
            Write-Host "已下载:$savePath"
        }
    }
}

# 断开连接
Disconnect-ExchangeOnline -Confirm:$false

方案二:Microsoft Graph API(开发集成首选)

适合嵌入到应用程序中,支持多语言(C#、Python等),扩展性更强。以下是Python示例:

1. 前置准备

在Azure AD注册应用,添加Delegated权限:Mail.Read(读取邮件权限)。

2. Python代码实现

import os
from msgraph.core import GraphClient
from azure.identity import UsernamePasswordCredential

# 配置参数
CLIENT_ID = "你的Azure应用客户端ID"
TENANT_ID = "你的租户ID"
USERNAME = "your-email@domain.com"
PASSWORD = "你的邮箱密码"
TARGET_FOLDER_NAME = "你的目标文件夹名称"
LOCAL_SAVE_DIR = "./exchange_attachments"

# 创建本地保存目录
os.makedirs(LOCAL_SAVE_DIR, exist_ok=True)

# 初始化Graph客户端
credential = UsernamePasswordCredential(
    client_id=CLIENT_ID,
    username=USERNAME,
    password=PASSWORD,
    tenant_id=TENANT_ID
)
client = GraphClient(credential=credential)

# 查找收件箱下的目标文件夹
inbox_folders = client.get("/me/mailFolders/inbox/childFolders").json()["value"]
target_folder = next((f for f in inbox_folders if f["displayName"] == TARGET_FOLDER_NAME), None)

if not target_folder:
    print(f"未找到文件夹:{TARGET_FOLDER_NAME}")
    exit()

# 获取文件夹内所有邮件(展开附件信息)
messages = client.get(f"/me/mailFolders/{target_folder['id']}/messages?$expand=attachments").json()["value"]

# 下载附件
for msg in messages:
    if "attachments" in msg:
        for att in msg["attachments"]:
            # 仅处理文件类型附件,跳过内嵌图片等
            if att["@odata.type"] == "#microsoft.graph.fileAttachment" and att["size"] > 0:
                att_content = client.get(f"/me/mailFolders/{target_folder['id']}/messages/{msg['id']}/attachments/{att['id']}/$value")
                save_path = os.path.join(LOCAL_SAVE_DIR, att["name"])
                with open(save_path, "wb") as f:
                    f.write(att_content.content)
                print(f"已保存:{save_path}")

关键注意事项

  • PowerShell方案需要用户自身邮箱权限,适合一次性批量操作
  • Graph API方案若需处理大于150MB的大附件,需使用createUploadSession分段下载逻辑
  • 生产环境中Graph API建议使用Client Credentials权限(而非用户名密码)提升安全性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 05:17:09