I normally don’t post scripts and batch files that I use, but I wanted to share this particular script because I use it all the time. VBScript files are nice because typically they are simply coded, and work across virtually all Windows-powered machines. You just have to throw the code in a .VBS file, and from there it can be executed in your batch files very easily.

The contents of the file are below, and once set up you’ll be able to send emails using any Gmail account straight from the command prompt. In the code there are two things that you need to configure: the email address and password of the account you want to send as. When executing the VBScript file you simply pass it three parameters: recipient email address, subject line, and the body of the email. There is an optional fourth parameter that it accepts which is the file path to a file you want to attach to the email. That’s it.

Why do I use this all the time? I can easily call this file from other scripts or batch files so that it sends me an email notification whenever something completes. Sometimes I use it just to have a nice history of when some of my batch files complete (or to verify that they even ran), but other times I will insert “dynamic” text into the body of the email. For example, if an error occurred I may have it put the error message in the body of the email. An alternative to that would be attaching a log file using the optional fourth parameter.

The nice thing about the way this script works is that you’ll be able to send emails without setting up an SMTP server on your machine. Of course you won’t be able to send out mass quantities of emails since Google limits you to around 500 sent messages per day, but that should be more than adequate for personal purposes.

Let’s take a look at what the code looks like…

Code begins here:

'Usage: cscript sendemail.vbs <email_recipient@example.com> "<subject_line>" "<email_body>" "<optional:email_attachment_path>" '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

^ That is the end of the code (Download the Script) ^

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):

Download a Zipped Copy of the VBScript

There Are 58 Comments

  1. quite interesting article, May you give us more examples how can make this script useful?

    • This script can be used for a lot of different things. I also use this in other VBScript files that I write as a way to send notifications when a task starts, ends, and any notifications it needs to send in between.

  2. Great idea. I’d like to use this for some automated alerts but unfortunately I’m behind a firewall. I would normally get aroud the firewall by setting up a port-forward over an SSH tunnel, creating a local port 8465 which is pointed at smtp.gmail.com port 465. I would then talk to localhost:8465 instead of smtp.gmail.com:465 and have the data passed on through the tunnel. Whilst this works with other mechanisms (such as sending via the blat utility, or using smail clients such as Thunderbird etc) it DOESN’T work for this.

    Any idea as to why? I don’t really understand vbscript or these CDO messaging objects so am at a bit of a loss. I have never seen something work directly to a host but NOT over a simple SSH tunnel. Is the CDO checking that the hostname returned by the server matches the name used to connect to it? Any ideas??? I’d love to get this working.

    • Unfortunately I think the CDO might be doing something behind-the-scenes that is preventing that from working. If you’re behind a firewall that doesn’t allow traffic over port 465 this could be pretty difficult to get working.

  3. Subscript out of range
    Line 18 ; Character 1

    Help?

    • Sounds like you aren’t passing it any parameters. Make sure you are running the script with the parameters that are required.

  4. hi Ryan,

    this piece of code is good , simple and easy to implement , I can now access my home network without having to call up and ask for recent IP..

    3 cheers..

    Bala

    • Ahhhh! Nice use of the script.

    • Hmm… how do you trigger the email? If you have some code to scrape whatismyip.com or similar and send the email as your public IP changes I’d be interested in seeing it. I have a UNIX script for this but not a Windows one.

      Having said that I just connect home using a dynamic IP updated by dns-o-matic myself but your’s is interesting if you don’t want to be tied to a service updating your DNS records.

  5. I get this error:

    C:\bin\vbssendemail\sendemail.vbs(36, 1) CDO.Message.1: The transport failed to connect to the server.

  6. Wow! Thanks man. I was looking for something like this for a family keylogger! Found my answer!

  7. This is great! I had a script that used to work for this and it broke back in April. This script works very well. I am using the AutoExNt service to run a batch file that obtains my external and internal IP address and emails me the information when the computer boots. Great in the case of my computer getting stolen or me just needing to know how to Remotely access my computer on what ever network I am connected to.

  8. I plan to carry this script around on my flash drive so at school(yes im still in school) I can access my email without downloading anything but I get an error saying “Subscript out of range” and it is a microsoft VBScrip runtime error. can anyone help

  9. i use this with uTorrent…when the torrent is done, i get an email…love it…

  10. Hi,
    I get this when I try to run it:
    sendemail.vbs(23, 2) CDO.Message.1: Protocol unknown
    (actually it says “A megadott protokoll ismeretlen” but it’s Hungarian :))
    The file exists what I pass as 3rd argument.
    Do you have any idea what’s wrong?

    • Funny thing is, I tried with absolute paths and it’s working. Shouldn’t it have to work with relative paths as well?

  11. I inspired on [autohotkey.com] and edit script, so it accept email body on stdin. In my opinion it is much better., I can pipe on it stdout of some script.
    What do you think?

    ‘Usage: echo “Email body” | cscript sendemail.vbs “” “” “”
    ‘Ex. No attach: echo “Email body” | cscript sendemail.vbs example@gmail.com “test subject line”
    ‘Ex. W/ attach: echo “Email body” | cscript sendemail.vbs example@gmail.com “test subject line” “c:\scripts\log.txt”

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

    Const fromEmail = “example@gmail.com”
    Const password = “examplepass”

    ‘****END OF CONFIGURATION
    ‘***********

    Dim emailObj, emailConfig
    Dim StdIn, emailBody
    emailBody = “”
    Set StdIn = WScript.StdIn
    Do While Not StdIn.AtEndOfStream
    emailBody = emailBody + vbNewLine + StdIn.ReadLine
    Loop
    Set emailObj = CreateObject(“CDO.Message”)
    emailObj.From = fromEmail
    emailObj.To = WScript.Arguments.Item(0)
    emailObj.Subject = WScript.Arguments.Item(1)
    emailObj.TextBody = emailBody

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

    Set emailConfig = emailObj.Configuration
    emailConfig.Fields(“[schemas.microsoft.com]) = “smtp.gmail.com”
    emailConfig.Fields(“[schemas.microsoft.com]) = 465
    emailConfig.Fields(“[schemas.microsoft.com]) = 2
    emailConfig.Fields(“[schemas.microsoft.com]) = 1
    emailConfig.Fields(“[schemas.microsoft.com]) = true
    emailConfig.Fields(“[schemas.microsoft.com]) = fromEmail
    emailConfig.Fields(“[schemas.microsoft.com]) = password
    emailConfig.Fields.Update

    emailObj.Send

    Set emailobj = nothing
    Set emailConfig = nothing

  12. I love it, though i am still very much new to this area of VBs is there a way of making it come from an anon or non existant account or is there a way of listing your emails. Also a good feature would be a pop up when the email is received.

    Thanks in advance, i will try and figure some of his out myself but any help is welcome

    Lanky_ninja

  13. Great script. I am a computer consultant and the thing I like about this is that when I write a script for clients they can always run this just by putting in the gmail address and pass.

    By the way, this works perfectly ‘behind’ a firewall. You don’t have to open any ports, unless some idiot is blocking OUTBOUND traffic which is VERY doubtful.

  14. Hi,

    I have used smtpserver name as the microsoft server name which my company uses & the port no but i am still getting following error:-
    C:\sendemail.vbs(36, 1) CDO.Message.1: The transport failed to connect to the server.

    Thanks,
    Vaibhav

    • one correction — I have used Microsoft Exchange Server Name

    • You can’t just update the server name. Things like the port number and other things will be different. Plus you have to make sure that your Exchange server is configured to send mail coming from the server where this script is running from.

  15. Hi Could someone dummy proof this one? I keep getting error after error.

    Thanks

  16. i was Googling around a few weeks for such a script, i found a lot, but nothing worked.
    finely, i found this one and it worked perfect.
    Thanks

  17. Thanks heaps for the script. Was looking for something for very long. Finally found your script which works perfect!!!

  18. Hi Guru ,
    while i execute the script the error was flashed like below

    D:\>cscript sendemail.vbs svce.arun@gmail.com “test”
    Microsoft (R) Windows Script Host Version 5.8
    Copyright (C) Microsoft Corporation. All rights reserved.

    D:\sendemail.vbs(19, 1) Microsoft VBScript runtime error: Subscript out of range

    • You aren’t passing it all of the required parameters. I gave this as the example:

      cscript sendemail.vbs [email_recipient@example.com] “[subject_line]” “[email_body]” “[optional:email_attachment_path]”

      So that means you passed it a subject line but not the body of the email. The path to the attachment is optional.

  19. Works great but I can’t seem to figure out how to get it to send an attachment?

    Is this the correct syntax?

    Dim emailObj, emailConfig
    Set emailObj = CreateObject(“CDO.Message”)
    emailObj.From = fromEmail
    emailObj.To = “test@gmail.com”
    emailObj.Subject = “test”
    emailObj.TextBody = “just a simple test”

    If WScript.Arguments.Count > 3 Then
    emailObj.AddAttachment = “c:\test.xls”
    End If

    • If you are hardcoding all the paths and not passing parameters to the script you need to change:

      If WScript.Arguments.Count > 3 Then
      emailObj.AddAttachment = “c:\test.xls”
      End If

      TO

      emailObj.AddAttachment = “c:\test.xls”

  20. Fantastic!

    I piped this through a .bat file in order to send to multiple users; and used Task Scheduler to set it up to repeat daily for a couple of weeks (reminder emails the boss wanted sent out). Works like a charm!

    Now if only I could get Linux to grok my vbscript d-:

    • Dear i’m getting the following error message.
      the error code was 0*80040217. The server response was not available.
      Plzzzzzzzzzzzzzzzzz help me!!!

  21. Looks great, but can’t get it to work, using W7 64 bit. Get Error: Expected end of statement, Code: 800A0401, Source Microsoft VBScript compilation error. Any suggestions would be greatly appreciated. Thanks.

  22. Hi
    This is probably a daft question and I am obviously missing something.
    I am trying to generate emails with a script and a one line message works fine but I am unable to insert carriage-returns and line feeds into the text.
    Any ideas?
    Mike

  23. Hi ,

    Its a great blog helping user with VBSCript. I m trying to send an email with attachment. I was successful in writing the script. I wrote a VBscript as below: However, I cannot create body of an email with multiple lines. Any help in this regards is much appreciated :

    Dim objOutl
    Set objOutl = CreateObject(“Outlook.Application”)
    Set objMailItem = objOutl.CreateItem(olMailItem)
    ‘comment the next line if you do not want to see the outlook window
    objMailItem.Display
    strEmailAddr = “bubby.bedi@gmail.com”
    objMailItem.Recipients.Add strEmailAddr
    objMailItem.Subject = ” Test Mail”
    dim strMsg
    strMsg = “This is the test example for your reference” & vbcrlf
    strMsg = strMsg & “I voted and gave you an excellent rating!”

    objMailItem.Attachments.Add “C:\Users\bedi\Desktop\Software Testing.docx”
    objMailItem.Send
    Set objMailItem = nothing
    Set objOutl = nothing

  24. For attachments, the path has to be absolute? I have the script located in a directory with the files I want attached, but if I just put the filename directly, it throws an error. I am not sure how I put the absolute path in, since some of the directories in the path have spaces in them. How can I get my situation to work?

    • Any ideas how to get file from a relative path? I had it working before, but for some reason can’t figure out what I did. I used something like “.\” or of that nature and it worked, but now I can’t figure out what I did or why isn’t working anymore.

  25. Brilliant! Used the script to return exams & score sheets to my 100+ students.

  26. Hi Ryan. Thanks for the great script. Any idea how to get relative path to work? I have files within the same directory as the script, but I tried various relative path parameters and none of them seem to work.

    • You’ll need to get the path of the script. I haven’t tested this, but you should be able to save the current path to a variable using something like this:

      scriptPath = Replace(WScript.ScriptFullName, WScript.ScriptName, “”)

    • Thanks for the reply. Sorry I am a scripting noob, but do I just copy that line into your email vbs script? Then for the argument when running the script, I just have to put the filename (ss.jpg), which is in the same directory?

  27. Dear Ryan, thanks for perfect script.

  28. thanks so much, the script is perfect.

  29. What a great and simple script !
    I just don’t get it to work.

    This is my error message:
    “sendemail.vbd(36, 1) (null): The message could not be sent to the SMPT server. The transport error code was 0×80040217. The server response was not available”

    Any idea, anyone?
    thanks !

    • Sounds like you may have a problem with the necessary ports not being open on the network you are sending from.

    • I need to create a script to send an automatic email to recipients who all are present in row no (A2) to (A10) in xls sheet and also to remove the duplicate email id’s in the particular column, Please help this would be great advantage to me.

  30. Very cool script i searched before but have no luck, very nice script and work
    without any problem. thanks

  31. Anyone find a way to have multi-line ability in the body of the email?

  32. thank you very much for this script. i mean it, this is very help full..

    a million thanks!

  33. Thanks. I was looking for a gmail example and you provided it exactly. It’s already in use in under 5 minutes!

  34. thank you soooooo much.

  35. Works great with Windows 2012 Server. I tried powershell but it just didn’t work. This just works great and easy to use!! Thanks.

Leave Your Comment


Message is the only required field.
Emails are not published.