7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PowerShellのSend-MailMessageを使ってバッチメールを送るメモ

Last updated at Posted at 2019-05-16

すべての環境に当てはまるわけじゃないのでご注意ください。

ps1ファイル

以下の内容でps1ファイルを作成する

hogehoge.ps1

$mail = @{
    from = "example@gmail.com";
    to = "example+to@gmail.com";
    smtp_server = "xxxxxxxxxx";
    smtp_port = 587;
    user = "example@gmail.com";
    password = "1234";
}

$subject = "件名";
$crlf = "`r`n";
$body = "おはようございます。" + $crlf;
$body += "つらつらつづる" + $crlf;
$body += " よろしくお願いします" + $crlf;

$encoding = ([System.Text.Encoding]::BigEndianUnicode); # 有効な値は、ASCII、UTF8、UTF7、UTF32、Unicode、BigEndianUnicode、Default、および OEM です https://docs.microsoft.com/ja-JP/previous-versions//dd347693(v=technet.10)


$password = ConvertTo-SecureString $mail["password"] -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $mail["user"], $password

Send-MailMessage -To $mail["to"] `
                 -Cc $mail["cc"] `
                 -From $mail["from"] `
                 -SmtpServer $mail["smtp_server"] `
                 -Subject $subject `
                 -Body $body `
                 -Credential $credential `
                 -Port $mail["smtp_port"] `
                 -UseSsl
                 -Encoding $encoding

#理由は不明だが、2バイト文字からBodyが始まると文字化けする場合があるので、そういう場合には、Bodyの先頭に1文字半角文字を入れると解消する場合がある。

batch

PS1ファイルを実行できるbatファイルを作成し、タスクへ登録する

batchファイル
@echo off
echo 開始..
powershell -NoProfile -ExecutionPolicy Unrestricted .\hogehoge.ps1
echo 完了!
pause > nul
exit

参考

Powershellを楽に実行してもらうには - Qiita

Send-MailMessage | Microsoft Docs

PowerShellを使って、SMTPでGmailを送信する - メモ的な思考的な

7
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?