2014/11/15

装置監視用自動電子メール送信スクリプト

装置監視用に自動で画面をキャプチャーしてメールを送り付けるスクリプトを作ったので、誰かの役に立てばとログを残しておく。 

OSはwindowsで、メール送信はOSに標準装備のWSH/VBscriptとバッチファイル、画面のキャプチャーはスクリーンショットというフリーソフトを使用。 スクリーンショットの本体であるPrtScrn.exeと以下のファイルを同じフォルダに置いてsendmail.batを実行すればOK(メールアドレスとsmtp設定は各自変更のこと)。

作成に用いた引用元を示したかったのだが、色々なページからソースを引っ張ってきたのでどれがどれかわからなくなってしまった…

sendmail.bat
@echo off

:LOOP

REM 3600sに1回送信。間隔を変えたければ3600を変更する。
timeout /T 3600 /NOBREAK >nul
PrtScrn.exe -f screenshot.png
cscript sendmail.vbs your@mail.address.jp screenshot.png
del screenshot.png

REM 永遠に自動ループするので、終わるときはCTRL+Cで強制終了。
goto LOOP
sendmail.vbs
'引数より送信先アドレスと貼付ファイル名を取得
Set args = WScript.Arguments
strAddress = args.item(0)
strAttachment = args.item(1)

Set oMsg = CreateObject("CDO.Message")

'メール送信元アドレス
oMsg.From = "my@mail.address.jp"
oMsg.ReplyTo = "no-reply@mail.address.jp"

'メール送信先アドレス
oMsg.To = strAddress
'oMsg.Cc = "cc先メールアドレス"
'oMsg.Bcc = "bcc先メールアドレス"

'メール本文
oMsg.Subject = "件名"
oMsg.TextBody = "本文" & vbCrLf & Now
oMsg.AddAttachment strAttachment

'SMTPサーバとサーバポートの指定
oMsg.TextBodyPart.Charset = "ISO-2022-JP"
oMsg.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/" + "sendusing") = 2
oMsg.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/" + "smtpserver") = "smtp.mail.address.jp"
oMsg.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/" + "smtpserverport") = 25

'SMTP認証が必要な時はコメントを外しユーザーネームとパスワードを記入
'oMsg.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/" + "smtpauthenticate") = true
'oMsg.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/" + "sendusername") = "ユーザーネーム記入"
'oMsg.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/" + "sendpassword") = "メールパスワード記入"

'SSL送信が必要な時はコメントを外す
'oMsg.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/" + "smtpusessl") = true

oMsg.Configuration.Fields.Update
oMsg.Send