Enumerating the If... Then: Scripts

Monday, September 21, 2009

VBScript: Sendmail script


main()

function IfYouGetCaught(strErr)

if len(strErr) > 1 then
strErrorLine = strErrorLine + strErr
strErrorLine = strErrorLine + vbnewline + vbnewline
end if

strErrorLine = strErrorLine + "usage: cscript sendmail.vbs /from:[from address] /to:[address1,address2] [/subject:[subject]] [/body:[message] [/attachment:path1,path 2]" & vbnewline & _
vbnewline & _
"The arguments subject and body are optional." & vbnewline & _
vbnewline & _
"If /body:stdin is specified, then body will accept stdin as the body of the Email."
wscript.echo strErrorLine
WScript.Quit
end function

Function IsUsingCscript()
Dim iPosition
iPosition = InStr( LCase(WScript.FullName) , "cscript.exe" )
If iPosition = 0 Then IsUsingCscript = False Else IsUsingCscript = True
End Function


function main()

Set objMessage = CreateObject("CDO.Message")

If Not IsUsingCscript() Then
IfYouGetCaught("You must use cscript.exe to run this script.")
End If


If WScript.Arguments.count < 1 then
IfYouGetCaught("default")
end If

if len(WScript.Arguments.Named("from")) < 1 then
IfYouGetCaught("You need to provide a from address.")
else
objMessage.From = WScript.Arguments.Named("from")
end if

if len(WScript.Arguments.Named("to")) < 1 then
IfYouGetCaught("You need to provide at least one to address.")
else
objMessage.To = WScript.Arguments.Named("to")
' ToAddresses = split(WScript.Arguments.Named("to"), ",")
end if

if len(WScript.Arguments.Named("subject")) < 1 then
else
objMessage.Subject = WScript.Arguments.Named("subject")
' ToAddresses = split(WScript.Arguments.Named("to"), ",")
end if


if len(WScript.Arguments.Named("attachment")) > 1 then

Attachments = split(WScript.Arguments.Named("attachment"), ",")

if ubound(Attachments) >= 0 then
for each item in Attachments
objMessage.AddAttachment item
next
end if

end if



'accept stdin as objMessage.Textbody
if ( WScript.Arguments.Named("body") = "stdin" ) then
objMessage.Textbody = Wscript.StdIn.ReadAll()
else
objMessage.Textbody = WScript.Arguments.Named("body")
end if



objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "www.dynamicfunds.com"
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objMessage.Configuration.Fields.Update

objMessage.Send

end function