73 lines
2.4 KiB
PowerShell
73 lines
2.4 KiB
PowerShell
# Download-AttachmentsFrom.ps1 -- Download attachments from a specific sender
|
|
param(
|
|
[Parameter(Mandatory)]
|
|
[string]$SenderEmail,
|
|
|
|
[string]$OutputFolder = (Join-Path $PSScriptRoot ".." "downloads" $SenderEmail.Split("@")[0])
|
|
)
|
|
|
|
$ErrorActionPreference = "Stop"
|
|
|
|
# Load modules
|
|
Import-Module (Join-Path $PSScriptRoot "Logger.psm1") -Force
|
|
Import-Module (Join-Path $PSScriptRoot "GraphHelper.psm1") -Force
|
|
|
|
# Load settings
|
|
$settingsPath = Join-Path $PSScriptRoot ".." "config" "settings.json"
|
|
$settings = Get-Content $settingsPath -Raw | ConvertFrom-Json
|
|
$settingsHash = @{
|
|
TenantId = $settings.TenantId
|
|
ClientId = $settings.ClientId
|
|
ClientSecret = $settings.ClientSecret
|
|
MailboxUser = $settings.MailboxUser
|
|
}
|
|
|
|
# Init logger
|
|
$logDir = Join-Path $PSScriptRoot ".." "logs"
|
|
Initialize-Logger -LogDirectory $logDir -Level "Info"
|
|
|
|
Write-Log "Searching emails from: $SenderEmail"
|
|
|
|
# Search emails from sender across inbox and archive
|
|
$user = $settingsHash.MailboxUser
|
|
$filter = [uri]::EscapeDataString("from/emailAddress/address eq '$SenderEmail' and hasAttachments eq true")
|
|
$folders = @("inbox", "archive")
|
|
$messages = @()
|
|
|
|
foreach ($folder in $folders) {
|
|
$endpoint = "/users/$user/mailFolders/$folder/messages?`$top=100&`$select=id,subject,from,receivedDateTime,hasAttachments&`$filter=$filter"
|
|
try {
|
|
$result = Invoke-GraphRequest -Endpoint $endpoint -Settings $settingsHash
|
|
$count = @($result.value).Count
|
|
Write-Log "Folder '$folder': found $count email(s)"
|
|
$messages += @($result.value)
|
|
}
|
|
catch {
|
|
Write-Log "Folder '$folder': error or not found, skipping" -Level Warn
|
|
}
|
|
}
|
|
Write-Log "Found $($messages.Count) emails with attachments from $SenderEmail"
|
|
|
|
if ($messages.Count -eq 0) {
|
|
Write-Log "No emails with attachments found. Done."
|
|
exit 0
|
|
}
|
|
|
|
# Create output folder
|
|
if (-not (Test-Path $OutputFolder)) {
|
|
New-Item -ItemType Directory -Path $OutputFolder -Force | Out-Null
|
|
}
|
|
|
|
$totalFiles = 0
|
|
foreach ($msg in $messages) {
|
|
$subject = $msg.subject
|
|
$date = ([datetime]$msg.receivedDateTime).ToString("yyyy-MM-dd")
|
|
Write-Log "Processing: [$date] $subject"
|
|
|
|
$savedFiles = Get-MailAttachments -Settings $settingsHash -MessageId $msg.id -TargetPath $OutputFolder
|
|
$totalFiles += $savedFiles.Count
|
|
}
|
|
|
|
Write-Log "Done. Downloaded $totalFiles file(s) to: $OutputFolder"
|
|
Write-Host "`nOutput folder: $OutputFolder"
|