【ツールの概要】
・メールを送信するPowerShellスクリプトその②。
1はこれ↓
【PowerShell】(PCメンテナンス用)メール送信 - うまく動けばいいな!
・より汎用的にしました。
【環境(使っている環境)】
・Windows10Pro
・Powershell ver2.0以降
※他のWindowsでも動くか→7以降なら動くと思われる。
【ソース(sendmailtest.ps1)】
#param Param($fromaddress,$Totemp,$Cctemp,$Bcctemp,$MailSv,$Port,$userId,$pwd,$Subject,$Bodyfilepath) $scriptPath = $MyInvocation.MyCommand.Path $To = $Totemp -split "," $Cc = $Cctemp -split "," $Bcc = $Bcctemp -split "," #本文整形 $Body=(Get-Content -Path $Bodyfilepath) -join "`r`f" $pwd = $pwd | ConvertTo-SecureString -AsPlainText -Force $cred = New-Object System.Management.Automation.PSCredential $userId,$pwd $Encode = [System.Text.Encoding]::UTF8 Send-MailMessage ` -To $To ` -From $fromaddress ` -Cc $Cc ` -Bcc $Bcc ` -SmtpServer $MailSv ` -Credential $cred ` -UseSsl ` -Encoding $Encode ` -Port $Port ` -Subject $Subject ` -Body $Body $scriptfol = Split-Path $MyInvocation.MyCommand.Path -Parent $logfile = $scriptfol+ "\SendmailPS.log" $Now=Get-Date -Format "yyyy/MM/dd_HH:mm:ss" #要素数取得(一つの場合文字列長取得) $fromlen=$fromaddress.Length $Tolen=$To.Length $Cclen=$Cc.Length $Bcclen=$Bcc.Length #ログ出力 echo `r`nDate`t$Now,from`t$fromlen`t$fromaddress,To`t$Tolen`t$To,Cc`t$Cclen`t$Cc,Bcc`t$Bcclen`t$Bcc,MSV`t$MailSv,Port`t$Port,Sub`t$Subject,Body`t$Body | Add-Content $logfile -Encoding UTF8
【使用方法】
・paramを参考に送信に必要な設定をすべて引数で指定します。
・本文は$Bodyfilepathにファイルを置きその中に記載します。
・ログもどきがスクリプトと同じ場所に出力します。
・from、to、cc、bcc、を複数指定するときはダブルクォーテションで括り、カンマで区切ります。
カンマ区切りをスクリプト内で配列に変換(Split)します。
【説明】
・本文を外部ファイル化することで動的に。改行にも対応します。
・複数宛先の指定も「使用方法」のとおり簡単です。
・Portやサーバが固定ならそれも外部ファイル化できます。
・Bodyfilepathと同じ要領で添付ファイル($attachment)も追加できます。
【総評】
他のプログラムなどから柔軟に呼び出せるようにしました。
powershellもwshから呼び出せるので便利。
例えばこんな感じですね(VBA。変数命名については勘弁してください←)。
'引数を指定(内容は察してください、f_path以外は変数そのまま送るイメージ) strmailP = fromadd & " " & toadd & " " & ccadd & " """ & strBccAdd & """ " & smtpSV & " " & port & " " & UserID & " " & Password & " '" & mailtitle & "' '" & f_path & "'" & " 0" Set Wsh = CreateObject("Wscript.shell") strPath = ThisWorkbook.Path & "\mailsend.ps1" wrunexec = Wsh.Run("powershell -ExecutionPolicy RemoteSigned " & strPath & " " & strmailP, 0, True)
・・・横に長い。