本記事で使用しているSmtpClientは2018年現在非推奨となっています。
下記記事で紹介しているMailKitをご使用ください。
PowerShellを使ってメール送信する機会が増えてきたので、処理を関数化してみました。
function sendMail(
$UserID, #ユーザーID
$UserPassword, #パスワード
$MailFrom, #From
$MailToAry, #To(配列で指定)
$MailCcAry, #Cc(配列で指定)
$MailBccAry, #Bcc(配列で指定)
$MailSubject, #件名
$MailBody, #本文
$MailAtthPathAry, #添付ファイルのパス(配列で指定)
$MailEncoding = "utf-8", #本文と件名のエンコード
$MailServer = "smtp.office365.com", #メールサーバー
$MailPort = 587, #ポート番号
$SSLFlg = $true #SSLを使用するかどうかを指定
){
#Message
$Msg = New-Object System.Net.Mail.MailMessage
$Msg.From = $MailFrom
foreach($MailTo in $MailToAry){
$Msg.To.Add($MailTo)
}
if($MailCcAry -is [array]){
foreach($MailCc in $MailCcAry){
$Msg.CC.Add($MailCc)
}
}
if($MailBccAry -is [array]){
foreach($MailBcc in $MailBccAry){
$Msg.Bcc.Add($MailBcc)
}
}
$Msg.Subject = $MailSubject
$Msg.SubjectEncoding = [System.Text.Encoding]::GetEncoding($MailEncoding);
$Msg.Body = $MailBody
$Msg.BodyEncoding = [System.Text.Encoding]::GetEncoding($MailEncoding);
if($MailAtthPathAry -is [array]){
foreach($MailAtthPath in $MailAtthPathAry){
if([System.IO.File]::Exists($MailAtthPath)){
$MailAtth = New-Object System.Net.Mail.Attachment($MailAtthPath)
$Msg.Attachments.Add($MailAtth)
}
}
}
#Server
$Smtp = New-Object System.Net.Mail.SmtpClient($MailServer, $MailPort)
$Smtp.Credentials = New-Object System.Net.NetworkCredential($UserID, $UserPassword)
$Smtp.EnableSsl = $SSLFlg
$Smtp.Send($Msg)
$Msg.Dispose()
$Smtp.Dispose()
return
}
sendMail "user@hogehogexxx.onmicrosoft.com" "passxxxx" "from@hogehogexxx.onmicrosoft.com" @("to@hogehogexxx.onmicrosoft.com") "" "" "テストメール" "本文1`r`n本文2" @("C:\Test\Test1.docx", "C:\Test\Test2.docx")
Send-MailMessageコマンドレットの方が簡単なのですが、細かく制御できるSmtpClientクラスの方を使っています。
また、標準ではOffice 365のサーバーからメール送信するように初期値を設定しています。
参考Webページ
- 【PowerShell】Windows PowerShell を使用して GMail や Office 365 からメールを送信する
- https://blogs.technet.microsoft.com/junichia/2011/12/08/powershellwindows-powershell-gmail-office-365/
- SmtpClientクラスを使ってメールを送信する
- https://dobon.net/vb/dotnet/internet/smtpclient.html
- CC、BCC、添付ファイル、優先順位などを指定してメールを送信する
- https://dobon.net/vb/dotnet/internet/smtpmail2.html

![[PowerShell]MailKitを使ってメールを送信する方法](https://www.ka-net.org/blog/wp-content/uploads/eyecatch-PowerShell-120x120.png)















この記事へのコメントはありません。