Logon Script to Send Email Notifications - Creating and sending the notification email
(Page 3 of 4 )
Now that we have all of the information that we need, it’s time to write a function that will create and send an email with it. I’ll keep the explanations here brief. If you would like more information, I have an entire article dedicated to the topic.
Sending Emails Using CDO in WSH
In short, this function needs to create an email message and send it using the details provided. Most of the details need to be provided as constants at the beginning of the script. The body of the email will be passed as arguments to the function.
Function SendMail(strBody)
Set objEmail = CreateObject("CDO.Message")
With objEmail
.From = ADMIN_EMAIL
.To = ADMIN_EMAIL
.Subject = "Logon Notification"
.HTMLBody = strBody
The function begins by connecting to the CDO object and assembling the message object to send. Like any email, it requires a To and From address along with a subject line and body.
.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = SMTP_SERVER
.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = SMTP_PORT
If USE_AUTHENTICATION Then
.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusername") = SMTP_USER
.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendpassword") = SMTP_PASS
End If
If SMTP_SSL Then
.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
End If
.Configuration.Fields.Update
The next section of code sets all of the required SMTP server settings for the CDO object to use. I’ve allowed for both simple and authenticated SMTP access. Variables at the beginning of the script are used to set these requirements.
On Error Resume Next
Err.Clear
.Send
If Err.number <> 0 Then
SendMail = Err.Description
Else
SendMail = "The server did not return any errors."
End If
On Error Goto 0
End With
End Function
We end our function by actually sending the email message. A little error-handling ensures that the script doesn’t break if for some reason the mail cannot be sent. With a little tweaking, you could easily make this function retry after a period of time, if this were to happen.
Next: Putting it all together >>
More Windows Scripting Articles
More By Nilpo