Wednesday, July 25, 2012

VBScript to Send Emails with Gmail

Code begins here:

'Usage: cscript sendemail.vbs "" "" ""
'Ex. No attach: cscript sendemail.vbs example@gmail.com "test subject line" "test email body"
'Ex. W/ attach: cscript sendemail.vbs example@gmail.com "test subject line" "test email body" "c:\scripts\log.txt"

'***********
'****CONFIGURE THE FROM EMAIL ADDRESS AND PASSWORD

Const fromEmail = "email_sender@gmail.com"
Const password = "password"

'****END OF CONFIGURATION
'***********

Dim emailObj, emailConfig
Set emailObj = CreateObject("CDO.Message")
emailObj.From = fromEmail
emailObj.To = WScript.Arguments.Item(0)
emailObj.Subject = WScript.Arguments.Item(1)
emailObj.TextBody = WScript.Arguments.Item(2)

If WScript.Arguments.Count > 3 Then
emailObj.AddAttachment WScript.Arguments.Item(3)
End If

Set emailConfig = emailObj.Configuration
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = true
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendusername") = fromEmail
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendpassword") = password
emailConfig.Fields.Update

emailObj.Send
Set emailobj = nothing
Set emailConfig = nothing



You can see that the code starts with example usage of how you can call the VBScript file. Given the nature of executing VBScript files you may or may not have to include the “cscript” portion, but in general you are always better off having it there to ensure that it will run on your computer just fine. Here’s an example of what it looks like when being executed from the command prompt:
vbscript send email gmail.png
Note: The “sendemail.vbs” file was located at the root of the C Drive when I ran this.
Armed with this script you should be able to take it and throw it into batch files, or call it from anywhere that can execute things via the command line. One thing you may want to consider is creating an extra email account just for sending these emails. Not only will that keep your “sent mail” clean in your primary Gmail account, but it will also be a bit more secure since the password for the sender account is stored in plain text within the script.
Here is a nicely formatted version of the VBScript from above that you can download, and have all ready to go for you (after you fill in the two email/password inside the script file, of course):

script download : http://cybernetnews.com/wp-content/uploads/2010/08/sendemail.zip
source: http://cybernetnews.com/vbscript-send-emails-using-gmail/

No comments: