Outlook で毎日届くメールの中から「特定のキーワードのメールを抽出したい」「添付ファイルだけ自動保存したい」と思ったことはありませんか?
この記事では、PowerShell を使って Outlook の受信メールから以下の情報を自動取得する方法をご紹介します。
PowerShell + Outlook の前提条件
この方法は以下の環境で動作します:
- Windows PC
- Microsoft Outlook(M365 / Office 2019など)
- PowerShell(バージョン5以上推奨)
※ Outlook はローカルにインストールされている必要があります。
メール情報を取得してテキストファイルに出力するスクリプト
以下のスクリプトでは、件名に「請求書」が含まれるメールを対象に、件名・差出人・本文(先頭100文字)・添付ファイル名を取得し、テキストファイルに保存します。
$outputPath = "C:\Temp\outlook_mails.txt"
$dir = Split-Path $outputPath
if (-not (Test-Path $dir)) {
New-Item -Path $dir -ItemType Directory | Out-Null
}
$keyword = "請求書"
$outlook = New-Object -ComObject Outlook.Application
$namespace = $outlook.GetNamespace("MAPI")
$inbox = $namespace.GetDefaultFolder([Microsoft.Office.Interop.Outlook.OlDefaultFolders]::olFolderInbox)
$messages = $inbox.Items
$messages.Sort("[ReceivedTime]", $true)
"" | Set-Content -Path $outputPath -Encoding UTF8
foreach ($mail in $messages) {
if ($mail.MessageClass -eq "IPM.Note" -and $mail.Subject -like "*$keyword*") {
Add-Content -Path $outputPath -Value "件名: $($mail.Subject)"
Add-Content -Path $outputPath -Value "差出人: $($mail.SenderName)"
$bodyPreview = $mail.Body.Substring(0, [Math]::Min(100, $mail.Body.Length))
Add-Content -Path $outputPath -Value "本文: $bodyPreview"
if ($mail.Attachments.Count -gt 0) {
Add-Content -Path $outputPath -Value "添付ファイル:"
for ($i = 1; $i -le $mail.Attachments.Count; $i++) {
$attachment = $mail.Attachments.Item($i)
Add-Content -Path $outputPath -Value " - $($attachment.FileName)"
}
} else {
Add-Content -Path $outputPath -Value "添付ファイル: なし"
}
Add-Content -Path $outputPath -Value "-----------------------------"
}
}
出力結果の例
件名: 4月分請求書のお知らせ
差出人: 経理部
本文: いつもお世話になっております。4月分の請求書をお送りします...
添付ファイル:
- invoice_2024-04.pdf
-----------------------------
まとめ
PowerShell を使えば、Outlook のルーチンワークを自動化することができます。
キーワードでの絞り込みや添付ファイルの保存を組み合わせれば、請求書処理や日報収集の自動化にも活用できます。
自動化できることはどんどん任せて、業務効率をアップしましょう!