【完全解説】PowerShellのSend-MailMessageでメール送信する方法|ログ通知・監視にも使える便利コマンド!

Windows

「バッチ処理や監視スクリプトの結果をメールで通知したい」
「PowerShellから自動でメールを送りたいけど、どうやればいいの?」

そんな方に最適なのが、PowerShellのSend-MailMessageコマンドレットです。

この記事では、Send-MailMessageの基本的な使い方から、GmailやSMTPの設定例、実用的な活用方法まで、初心者にもわかりやすく丁寧に解説します。

スポンサーリンク

Send-MailMessageとは?

Send-MailMessageは、PowerShellからSMTP経由でメールを送信できるコマンドレットです。

以下のようなシーンで活用されます:

  • バッチ処理完了の通知メール送信
  • エラー発生時のアラート
  • ファイル・ログの自動送信
  • 定期レポートの配信

Send-MailMessage は公式で非推奨。

基本的な構文と引数の意味

最小構成のサンプル:

Send-MailMessage `
  -From "sender@example.com" `
  -To "receiver@example.com" `
  -Subject "テストメール" `
  -Body "これはPowerShellから送信したテストメールです。" `
  -SmtpServer "smtp.example.com"

よく使う引数一覧:

引数説明
-From送信元アドレス
-To宛先(複数可)
-Cc/-BccCC / BCC送信先
-Subjectメールの件名
-Body本文
-BodyAsHtmlHTML形式の本文として送信
-SmtpServer使用するSMTPサーバーのアドレス
-PortSMTPのポート番号(通常587)
-UseSslSSL接続が必要な場合に指定
-Credential認証が必要な場合のログイン情報

SMTPサーバーの設定例(GmailやOffice365)

Gmailを使う例:

$securePassword = ConvertTo-SecureString "アプリパスワード" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential("yourgmail@gmail.com", $securePassword)

Send-MailMessage `
  -From "yourgmail@gmail.com" `
  -To "recipient@example.com" `
  -Subject "Gmailから送信" `
  -Body "これはGmail経由で送信したメールです。" `
  -SmtpServer "smtp.gmail.com" `
  -Port 587 `
  -UseSsl `
  -Credential $credential

Gmailでは「アプリ パスワード」の設定が必要です(2段階認証が有効な場合)。

Office365/Microsoft 365を使う例:

$securePassword = ConvertTo-SecureString "yourpassword" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential("your365email@domain.com", $securePassword)

Send-MailMessage `
  -From "your365email@domain.com" `
  -To "recipient@example.com" `
  -Subject "Office 365から送信" `
  -Body "これはOffice 365経由で送信したメールです。" `
  -SmtpServer "smtp.office365.com" `
  -Port 587 `
  -UseSsl `
  -Credential $credential

添付ファイル付きメールを送る方法

Send-MailMessage `
  -From "sender@example.com" `
  -To "receiver@example.com" `
  -Subject "ログファイルの送信" `
  -Body "添付ファイルをご確認ください。" `
  -SmtpServer "smtp.example.com" `
  -Attachments "C:\Logs\log.txt"

複数ファイルを送る場合は、配列で渡します:

-Attachments @("C:\Logs\file1.txt", "C:\Reports\file2.csv")

HTML形式のメールを送信する例:

$htmlBody = @"
<h2>サーバー状態レポート</h2>
<p>CPU使用率: <b>45%</b></p>
<p>メモリ使用率: <b>60%</b></p>
<p style='color:green'>すべてのサービスは正常に動作しています。</p>
"@

Send-MailMessage `
  -From "monitoring@example.com" `
  -To "admin@example.com" `
  -Subject "サーバー状態レポート" `
  -Body $htmlBody `
  -BodyAsHtml `
  -SmtpServer "smtp.example.com"

エラー通知・ログ報告への活用例

スクリプト実行後に結果を通知する例:

try {
    # 何らかの処理
    Write-Output "処理成功"
} catch {
    $errorMessage = $_.Exception.Message
    Send-MailMessage `
      -From "alert@example.com" `
      -To "admin@example.com" `
      -Subject "エラー通知" `
      -Body "処理中にエラーが発生しました:$errorMessage" `
      -SmtpServer "smtp.example.com"
}

サーバー監視とレポート送信の例:

# サーバー状態の取得
$cpuUsage = Get-Counter '\Processor(_Total)\% Processor Time' | Select-Object -ExpandProperty CounterSamples | Select-Object -ExpandProperty CookedValue
$memoryInfo = Get-CimInstance Win32_OperatingSystem | Select-Object -Property TotalVisibleMemorySize, FreePhysicalMemory

# メモリ使用率を計算
$memoryUsage = (($memoryInfo.TotalVisibleMemorySize - $memoryInfo.FreePhysicalMemory) / $memoryInfo.TotalVisibleMemorySize) * 100

# レポート作成と送信
$body = "サーバー状態レポート`n"
$body += "CPU使用率: $([math]::Round($cpuUsage, 2))%`n"
$body += "メモリ使用率: $([math]::Round($memoryUsage, 2))%`n"

Send-MailMessage `
  -From "monitor@example.com" `
  -To "admin@example.com" `
  -Subject "サーバー状態レポート $(Get-Date -Format 'yyyy-MM-dd')" `
  -Body $body `
  -SmtpServer "smtp.example.com"

よくあるエラーとその対策

エラー内容対処法
The SMTP server requires a secure connection-UseSsl を付けてください
Authentication failedメールアドレスやパスワードの間違い、またはアプリパスワードの未設定
Send-MailMessage is not recognized古いPowerShellまたはPowerShell Coreでは未搭載。別の方法(.NET)を検討する必要があります
Unable to read data from the transport connectionポート番号の間違いやファイアウォールの設定を確認

パスワードを安全に扱う方法(セキュリティ対策):

# パスワードを安全に保存
$password = Read-Host -AsSecureString "パスワードを入力してください"
$credential = New-Object System.Management.Automation.PSCredential("youremail@example.com", $password)

# パスワードを暗号化してファイルに保存
$password | ConvertFrom-SecureString | Out-File "C:\secure\password.txt"

# 別の機会に暗号化されたパスワードを読み込んで使用
$securePassword = Get-Content "C:\secure\password.txt" | ConvertTo-SecureString
$credential = New-Object System.Management.Automation.PSCredential("youremail@example.com", $securePassword)

まとめ:自動メール送信で業務を効率化しよう

PowerShellのSend-MailMessageを使えば、スクリプトと連動したメール通知や報告の自動化が簡単に実現できます。

バックアップ完了、サービスの状態通知、ログ添付など、さまざまな場面で活躍するコマンドレットです。

ポイントまとめ

  • Send-MailMessageはSMTP経由でメールを送信できる
  • 認証・SSL・添付ファイルにも対応
  • Gmail・Office365の設定例あり
  • PowerShellスクリプトとの組み合わせで強力な通知システムを構築可能

コメント

タイトルとURLをコピーしました