Windows PowerShellでメールサーバーにメール送信するには、主に「Send-MailMessage」コマンドレットを利用します。このコマンドは、SMTPサーバー経由でメールを送信でき、認証情報やSSLの有無、ポート番号なども指定可能です。
以下に具体的な基本例と、日本語メール送信、認証ありの送信例を解説します。
1. 基本のメール送信コマンド
powershellSend-MailMessage `
-From 'from@example.com' `
-To 'to@example.com' `
-Subject 'Test Subject' `
-Body 'This is the email body.' `
-SmtpServer 'smtp.example.com'
-From:送信元メールアドレス-To:送信先メールアドレス-Subject:メール件名-Body:本文(プレーンテキスト)-SmtpServer:SMTPサーバーのホスト名またはIP
2. 日本語メールをUTF-8エンコードして送信する場合
powershellSend-MailMessage `
-From 'from@example.com' `
-To 'to@example.com' `
-Subject '件名' `
-Body '本文(日本語)' `
-SmtpServer 'smtp.example.com' `
-Encoding ([System.Text.Encoding]::UTF8)
日本語を含むメールは文字化け防止のため、-EncodingでUTF-8を指定します。
3. SMTP認証が必要な場合の例(ユーザー名・パスワード指定、SSL使用)
powershell# 認証情報の作成
$mUser = 'user@example.com'
$mPass = ConvertTo-SecureString 'yourpassword' -AsPlainText -Force
$mCred = New-Object System.Management.Automation.PSCredential ($mUser, $mPass)
# 送信コマンド
Send-MailMessage `
-From $mUser `
-To 'to@example.com' `
-Subject '件名(認証あり)' `
-Body '本文(認証ありメール)' `
-SmtpServer 'smtp.example.com' `
-Port 587 `
-Credential $mCred `
-UseSsl `
-Encoding ([System.Text.Encoding]::UTF8)
-Credential:認証情報-Port:SMTPポート(一般的に587や465)-UseSsl:SSL/TLS接続を有効化

