PowerShellでメールを送る
WSHならCDO
WSHでメールを送る場合はCDO(Collaboration Data Objects)を利用するのが定石です。
CDOを利用したメール送信サンプル(VBScript)
Set oMsg = CreateObject("CDO.Message") oMsg.From = "from@xxx.co.jp" oMsg.To = "to@xxx.co.jp" oMsg.Subject = "サブジェクト" oMsg.TextBody = "テストメッセージです" & vbCrLf & Now oMsg.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 oMsg.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = _ "smtp.xxx.co.jp" oMsg.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 oMsg.Configuration.Fields.Update oMsg.Send
PowerShellでもCDO?
Monad Beta2からCOMオブジェクトの利用がサポートされましたが、当時はCDOは未サポートでした。
参考:「COMオブジェクト呼び出し」の制限 - PowerShell Memo
現在の最新版である、PowerShell RC1でCDOを試してみると、あれま、利用できるではないですか。
いつからサポートされたのでしょうか。
CDOを利用したメール送信サンプル(PowerShell)
$sendusing = "http://schemas.microsoft.com/cdo/configuration/sendusing" $smtpserver = "http://schemas.microsoft.com/cdo/configuration/smtpserver" $smtpserverport = "http://schemas.microsoft.com/cdo/configuration/smtpserverport" $oMsg = new-object -com "CDO.Message" $oMsg.From = "from@xxx.co.jp" $oMsg.To = "to@xxx.co.jp" $oMsg.Subject = "サブジェクト" $oMsg.TextBody = "テストメッセージです" $oMsg.Configuration.Fields.Item($sendusing) = 2 $oMsg.Configuration.Fields.Item($smtpserver) = "smtp.xxx.co.jp" $oMsg.Configuration.Fields.Item($smtpserverport) = 25 $oMsg.Configuration.Fields.Update() $oMsg.Send()
※ブログのレイアウトの都合でWSHサンプルとは書き方を変えています。
PowerShellならSmtpClient
@ITでも紹介されていましたが、.NET 2.0ではSmtpClientクラスを利用することで、メール送信を簡単に行えます。
SmtpClientを利用したメール送信サンプル(PowerShell)
$mailer = new-object System.Net.Mail.SmtpClient("smtp.xxx.co.jp") $mailer.Send("from@xxx.co.jp","to@xxx.co.jp","サブジェクト","本文")
CDOのように冗長なコードを書かずともメールが送れますね。