Thursday, August 16, 2007

Send Email from Windows Batch/VBS File


Our scenario was we were trying to improve on the manual process that a previous network administrator was using where he was manually checking the server each night to make sure a script had run, obviously this isn't a process that can be duplicated very successfully across many clients (I kinda like my free time at night) so we wanted to set up a script which handled the normal network, disk, etc. issues and sent us an email when done.

There are some great alternatives to sending a script like the ones outlines in this article, How can I send an e-mail message from a script? on the Petri Knowledge Base however I prefer to use built-in windows functionality whenever I can as I don't have time to review everyone's source (if available) to make sure that it doesn't have an malicious stuff in it. There are obviously plenty of girations you can do to this script like storing your password securely in the registry, making the send script into it's own bat file that can be called from others and the list goes on but I wanted to get it out there for people struggling. The only thing that is needed is the smtp server, email address and password and you should be good to go.

Enjoy


Set Message = CreateObject("CDO.Message")

With Message


'==This section provides the configuration information for the remote SMTP server.
'==Normally you will only change the server name or IP.
.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2

' smtp authentication type
.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1

'Name or IP of Remote SMTP Server
.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "mail.yourserver.com"

'Server port (typically 25)
.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25

' username & you know what
.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "notifications@yourserver.com"
.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "notifications-password"


.Configuration.Fields.Update

'==End remote SMTP server configuration section==


.To = "smallbiz@yourserver.com"
.From = "notifications@yourserver.com"
.Subject = "Scripted Email Notification"
.TextBody = "This email was sent from a vbs file"

.Send

End With

MsgBox("Email Generated Successfully")

No comments: