Command line mail VBscript (with attachments)


Batch scripting on windows provides no way of sending emails. There are paid-for solutions like febootimail and even free solutions like SendEmail. In the main you should probably try using the latter as I haven’t maintained this VBscript for a long time. That in itself is probably a good thing as I’ve used it alot and never needed to update it!

Anyway it may help someone who is adding the functionality into their scripts.

The script has the syntax:

cscript mail2.vbs [/A:attachmentpath] [/S:sender] [/R:recipient] [/C:Message Content] [/J:subject][/M:mailserver]

for example

cscript mail2.vbs /A:myfile.zip /S:me@mydomain.com /R:you@yourdomain.com /C:”Hi, Here’s that zip file you wanted. Thanks Stu” /J:”zip file” /M:smtp.mydomain.com

Here’s the script:

'********************************************************************
'*
'* File:           MAIL2.VBS
'* Created:        April 2004
'* Last Revision   May 2013
'* Version:        1.1
'*
'* Main Function: Emails an attachment to recipient from sender
'* Usage: MAIL.VBS [/A:attachmentpath] [/S:sender] [/R:recipient] 
'*        [/C:Message Content] [/J:subject] [/M:mailserver
'*
'*
'********************************************************************

'OPTION EXPLICIT
'ON ERROR RESUME NEXT

'Define constants
CONST CONST_ERROR                   = 0
CONST CONST_WSCRIPT                 = 1
CONST CONST_CSCRIPT                 = 2
CONST CONST_SHOW_USAGE              = 3
CONST CONST_PROCEED                 = 4

'Declare variables
Dim strsubject, intOpMode, i
Dim strattachmentpath, strsender, strmessagecontent,  strrecipient, strmailserver
ReDim strArgumentArray(0)

'Initialize variables
strArgumentArray(0) = ""
strattachmentpath = ""
strsender = ""
strmessagecontent = ""
strrecipient = ""
strsubject = ""
strmailserver = ""

'Get the command line arguments
For i = 0 to Wscript.arguments.count - 1
    ReDim Preserve strArgumentArray(i)
    strArgumentArray(i) = Wscript.arguments.Item(i)
Next

'Check whether the script is run using CScript
Select Case intChkProgram()
    Case CONST_CSCRIPT
        'Do Nothing
    Case CONST_WSCRIPT
        WScript.Echo "Please run this script using CScript." & vbCRLF & _
        WScript.Quit
    Case Else
        WScript.Quit
End Select

'Parse the command line
intOpMode = intParseCmdLine(strArgumentArray, strattachmentpath, strsender, strmessagecontent, strrecipient, _
            strsubject,strmailserver)
If Err.Number then
    Print "Error 0x" & CStr(Hex(Err.Number)) & " occurred in parsing the command line."
    If Err.Description <> "" Then
        Print "Error description: " & Err.Description & "."
    End If
    call showusage()
    WScript.Quit
End If

Select Case intOpMode
    Case CONST_SHOW_USAGE
        Call ShowUsage()
    Case CONST_PROCEED
        Call mail(strattachmentpath, strsender, strmessagecontent, _
             strrecipient,strsubject,strmailserver)
    Case CONST_ERROR
        'Do nothing.
    Case Else                    'Default -- should never happen
        Print "Error occurred in passing parameters."
End Select

'********************************************************************
'*
'* Function intChkProgram()
'* Purpose: Determines which program is used to run this script.
'* Input:   None
'* Output:  intChkProgram is set to one of CONST_ERROR, CONST_WSCRIPT,
'*          and CONST_CSCRIPT.
'*
'********************************************************************

Private Function intChkProgram()

    ON ERROR RESUME NEXT

    Dim strFullName, strCommand, i, j

    'strFullName should be something like C:\WINDOWS\COMMAND\CSCRIPT.EXE
    strFullName = WScript.FullName
    If Err.Number then
        Print "Error 0x" & CStr(Hex(Err.Number)) & " occurred."
        If Err.Description <> "" Then
            If Err.Description <> "" Then
                Print "Error description: " & Err.Description & "."
            End If
        End If
        intChkProgram =  CONST_ERROR
        Exit Function
    End If

    i = InStr(1, strFullName, ".exe", 1)
    If i = 0 Then
        intChkProgram =  CONST_ERROR
        Exit Function
    Else
        j = InStrRev(strFullName, "\", i, 1)
        If j = 0 Then
            intChkProgram =  CONST_ERROR
            Exit Function
        Else
            strCommand = Mid(strFullName, j+1, i-j-1)
            Select Case LCase(strCommand)
                Case "cscript"
                    intChkProgram = CONST_CSCRIPT
                Case "wscript"
                    intChkProgram = CONST_WSCRIPT
                Case Else       'should never happen
                    Print "An unexpected program is used to run this script."
                    Print "Only CScript.Exe or WScript.Exe can be used to run this script."
                    intChkProgram = CONST_ERROR
            End Select
        End If
    End If

End Function

'********************************************************************
'*
'* Function intParseCmdLine()
'* Purpose: Parses the command line.
'* Input:   strArgumentArray    an array containing input from the command line
'* Output:  strattachmentpath              Attachment path
'*          strsender                 Senders email
'*          strmessagecontent           Message Content
'*          strrecipient                Recipient Email
'*          strsubject               Subject
'*          intParseCmdLine         is set to one of CONST_ERROR, CONST_SHOW_USAGE, CONST_PROCEED.
'*
'********************************************************************

Private Function intParseCmdLine(strArgumentArray, strattachmentpath, strsender, _
        strmessagecontent, strrecipient, strsubject,strmailserver)

    'ON ERROR RESUME NEXT

    Dim strFlag, i

    strFlag = strArgumentArray(0)

    If strFlag = "" then                'No arguments have been received
        Call ShowUsage()
        intParseCmdLine = CONST_ERROR
        Exit Function
    End If

    For i = 0 to UBound(strArgumentArray)
        strFlag = LCase(Left(strArgumentArray(i), InStr(1, strArgumentArray(i), ":")-1))
        If Err.Number Then            'An error occurs if there is no : in the string
            Err.Clear
        Else
            Select Case strFlag
                Case "/a"
                    strattachmentpath= Right(strArgumentArray(i), Len(strArgumentArray(i))-3)
                Case "/s"
                    strsender = Right(strArgumentArray(i), Len(strArgumentArray(i))-3)
                Case "/c"
                    strmessagecontent = Right(strArgumentArray(i), Len(strArgumentArray(i))-3)
                Case "/r"
                    strrecipient = Right(strArgumentArray(i), Len(strArgumentArray(i))-3)
                Case "/j"
                    strsubject = Right(strArgumentArray(i), Len(strArgumentArray(i))-3)
        case "/m"
                    strmailserver = Right(strArgumentArray(i), Len(strArgumentArray(i))-3)
                Case else
                    Print "Invalid flag " & """" & strFlag & """" & "."
                    Print "Please check the input and try again."
                    intParseCmdLine = CONST_ERROR
                    call showusage()
                    exit function
                End Select
        End If
    Next

    intParseCmdLine = CONST_PROCEED

End Function

'********************************************************************
'*
'* Sub ShowUsage()
'* Purpose: Shows the correct usage to the user.
'* Input:   None
'* Output:  Help messages are displayed on screen.
'*
'********************************************************************

Private Sub ShowUsage()
    wscript.echo vbCrLf
    wscript.echo "USAGE:"
    wscript.echo "------"
    wscript.echo "cscript mail.vbs [/A:Attachment Path] [/S:Sender's Email] [/R:Recipient's Email] [/C:Message Content] [/J:Subject Line] [/M:Mail Server"
End Sub

'********************************************************************
'*
'* Sub mail()
'* Purpose: Emails based on inputs
'* Input:   strattachmentpath      attachmentpath of the root of the search
'*          strsender     the search sender
'*          strmessagecontent   messagecontent to be retrieved
'*          strrecipient        the search recipient
'*          strUserName     name of the current user
'*          strPassword     password of the current user
'*          strsubject   an output file name
'* Output:  Results of the search are either printed on screen or saved in strsubject.
'*
'********************************************************************

Private Sub mail(strattachmentpath, strsender, strmessagecontent, _
    strrecipient, strsubject,strmailserver)

    dim objEmail

    'ON ERROR RESUME NEXT
    if ("" <> strsender AND "" <> strrecipient) then 
    Set objEmail = CreateObject("CDO.Message")

    objEmail.From = strsender
    objEmail.To = strrecipient
    objEmail.Subject = strsubject
    objEmail.Textbody = strmessagecontent
    if "" <> strattachmentpath then
          objEmail.AddAttachment strattachmentpath
        end if
    objEmail.Configuration.Fields.Item _
        ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
    objEmail.Configuration.Fields.Item _
        ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = _
            strmailserver
    objEmail.Configuration.Fields.Item _
        ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
    objEmail.Configuration.Fields.Update
    wscript.echo "Sending email to "&strsender & " from " & strrecipient & " via " & strmailserver
        objEmail.Send
    else
        wscript.echo "ERROR: Sender or Recipient not specified"
    end if
    
End Sub

'********************************************************************
'*
'* Sub Print()
'* Purpose: Prints a message on screen.
'* Input:   strMessage      the string to print
'*
'********************************************************************

Sub Print(ByRef strMessage)
    wscript.Echo  strMessage
End Sub

You can download the script from the link below:

Download

Last edited on 31st May 2013 – Fixed bug where the sender and recipient strings were assigned incorrectly in the mail sub.

Advertisements
Tagged , ,

2 thoughts on “Command line mail VBscript (with attachments)

  1. Anonymous says:

    Besides the fact that you intermixed sender and receiver and did not dim objEmail in your sendmail method, this is just exactly what i was looking for! Thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: