dScope Series III Scripting and automation
Emailing results from a script
There are instances, particularly when doing long term remote monitoring, where it can be useful to be able to set up a test script that emails results back to a different location. This can be set up to email when certain conditions are met and can give detailed reports of multiple parameters measured over time, such as a daily report of average RMS level etc, or a capture of a buffer of data on a failure condition. It is fairly easy to format the email as HTML so that tables, graphics and text formatting can be achieved in a standard format.Using CDO
To send an email requires an SMTP server of some kind. Windows 2000, XP and Windows Server 2003 ship with a free Microsoft component called CDO (Collaboration Data Objects) which allows scripts to connect to the MAPI (Messaging API) which in turn can access SMTP (Simple Mail Transfer Protocol) servers1. It is possible to use this method to send an email from most Windows PCs using VBScript (including dScope .dss scripts). There may be issues with Vista which apparently doesn't include the necessary files by default and will therefore need either CDO installed or a third party SMPT server 2, 3. The remainder of this is written assuming CDO is available.
Constructing the emails
Using CDO, you can send an email either as text or as HTML. If sending as text, it's quite easy to set up the content of the text email in a variable and then just send the text. If sending as HTML, it can be easier to set up the HTML as a file and then specify the file to send. See also this scripting note on constructing HTML from a script. Doing it this way also has an advantage that you can set up the first part of the file containing the HTML headers first in a separate file, and then append the remainder of the file constructed by the script. This avoids having to construct the entire email in the script each time.
Constructing an email in HTML is well documented elsewhere on the internet 4 - the main things to remember are to keep the HTML basic. Many of the newer features of HTML and style sheets are not well supported in email clients, and some features cause problems for web based email systems such as Hotmail®.
When the email is constructed as HTML and saved as a file, it is ready to be sent as an email.
Emailing the HTML file
There is quite a bit of configuration to do before it is possible to send an email from a script. This falls broadly into two parts: configuring the email, and configuring the SMTP server. Configuring the email consists of setting up the various parts of the email; the email address it is to be sent to, the subject line, who it is from etc. Configuring the server consists of setting which SMTP server to use and which user name and password to access it with. We do this in a script by creating the message CDO object and setting the parameters as shown below:
Set objMessage = CreateObject("CDO.Message") With objMessage .Subject = "Test email" .From = "Joe Bloggs <joe@bloggs.com>" .To = "fred_bloggs@bloggs.com" .Cc = "bob_bloggs@bloggs.com" 'For sending a text message: '.TextBody = "Greetings! This is a test email." & strMessage 'For sending an HTML message from file .CreateMHTMLBody "file://c:/test.html" End With |
That's the email constructed, and it's quite self explanatory. Normally in the script we would replace the various strings such as the email address with variables so that they can be configured easily in the script, or even be changed by the script.
Next we need to configure the server. This is done in a similar fashion by setting some more properties of the CDO message object created above:
'setting up constants: Const cdoSendUsingPickup = 1 'Send message using the local SMTP service pickup directory. Const cdoSendUsingPort = 2 'Send the message using the network (SMTP over the network). Const cdoAnonymous = 0 'Do not authenticate Const cdoBasic = 1 'basic (clear-text) authentication Const cdoNTLM = 2 'NTLM 'Set up the server With objMessage.Configuration.Fields 'This section provides the configuration information for the remote SMTP server. 'How to send the email .Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = cdoSendUsingPort 'Name or IP of Remote SMTP Server .Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "mail.domain.com" 'Type of authentication, NONE, Basic (Base64 encoded), NTLM .Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = cdoBasic 'Your UserID on the SMTP server .Item ("http://schemas.microsoft.com/cdo/configuration/sendusername") = "JoeB" 'Your password on the SMTP server .Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "Password" 'Server port (typically 25) .Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 'Use SSL for the connection (False or True) .Item ("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = False 'Connection Timeout in seconds '(the maximum time CDO will try to establish a connection to the SMTP server) .Item ("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60 .Update End With 'End remote SMTP server configuration section |
Again we would normally set up the various configuration options as variables so the configuration could be set in one section near the beginning of the script, but this illustrates the principles involved. The various options and how to use them and what they mean are beyond the scope of this note. The above is a fairly common configuration and should work in many cases. There are several sites on the internet that may be helpful if you have problems.5.
We are now ready to send the email, and this consists very simply of the line:
objMessage.Send |
While this may be helpful once everything is de-bugged, initially at least, it may help to have something more like:
On error resume next objMessage.Send If Not Err.Number = 0 then msgbox "Failed. Error : " & Err.Number & ": " & Err.description , vbexclamation, "Email Script" Else msgbox "Email successfully sent", vbinformation, "Email Script" End If |
so that we are able to see what errors are occurring. Note that if this is used for remote monitoring, the message box appearing when the email is successfully sent will stop the script executing until the message box is cleared.
Embedding Graphics
It can be very useful to be able to embed a graph or FFT trace into an email along with results. In order to do this, the graphic file must attached to the email and then imported into the HTML using the <img> tag. You can attach multiple files and embed them into the HTML in this way. Normally the <img> tag makes reference to a file in a folder, so the syntax is slightly different to make it refer to the attached graphic. The process consists of defining the files to be embedded, first as the name they physically exist with on the local computer:
' Name of attachments (file names) strAttach(1) = "graph1.png" strAttach(2) = "graph2.png" |
Then as the name they will be attached to the email as...
' Reference name of attachments (must be reflected in HTML in strBodyFile) if embedding graphics strAttachRef(1) = "trace1.png" strAttachRef(2) = "trace2.png" |
These are attached to the email as shown below, where the variable strAttachPath is the path to the folder on the local computer where the image to be attached is located. These lines go in with the email configuration shown above.
'Attach files for embedding, such as graphics etc. objMessage.AddRelatedBodyPart strAttachPath & strAttach(1), strAttachRef(1), 1 objMessage.AddRelatedBodyPart strAttachPath & strAttach(2), strAttachRef(2), 1 |
We now have the files attached to the email, but in order to embed them into the HTML, we will need to use a slightly different form of <img> tag:
<p style='text-align: center;'> <img alt='Trace Export' src="cid:trace1.png"> <br /> </p> <hr /> <p style='text-align: center;'> <img alt='Trace Export' src='cid:trace2.png'> <br /> </p> |
Note in particular the "cid" at the beginning of the src attribute of the <img> tag.
Example Script
There is an example script available for download here. This is a small zip file containing four files that can be configured to send an example HTML email. The files are a VB script "send email.vbs", a sample HTML report "results_file.html" and a couple of dScope graph exports "graph1.png" and "graph2.png". To use them, you will need to:
- Unzip the files into an appropriate folder - the location is not important.
- Modify the script "send email.vbs" in a text editor to reflect your settings, in particular, in the "initialisation" section:
- Set the email address to send the email to (strEmailTo)
- Set the return email address (strEmailFrom)
- Set the name or IP address of your email server (strMailServer)
- Set the user name for your email server (strUserName)
- Set the password for your email server (strPassword) or leave it blank to be prompted for it when the script runs if you don't want the password visible in the script
- Change the path to the HTML results file to show the path where you unzipped the files so that the script can find the example HTML file. (strBodyPath)
- Change the path to the attachments to show the path where you unzipped the files so that the script can find the example graphs. (strAttachPath)
- Optionally you can also set a Cc address, change the name of the sender and subject line etc.
- You should then be able to run the script by double clicking on it
All being well, you should get a message that the email has been successfully sent. If not, you will get an error message stating what the error number is, and hopefully a description of the problem. Since this is a common technique for sending emails, particularly from ASP (Microsoft Active Server Pages) web sites, there is a wealth of information out there on the internet for resolving problems with server configurations etc.
Incorporating sending an email into a dScope test script
There is almost no end to what you can do with this code as far as using it with dScope goes. Typically it will be used to email results back to the user if the dScope is in a remote location monitoring a signal. In this case the script would be left running monitoring whatever parameters are required, and, upon encountering a particular condition (say the presence of a test signal or a fault condition) the script would take a series of measurements or capture a waveform, compile it into an HTML email and send it. The script could also be set to make constant measurements over a long duration, keeping track of minimum, maximum and average readings and email these at pre-determined intervals. The time when the results are measured can be set by using the
Now()
method in VB Script. If taking measurements that traverse midnight, beware of using the timer()
method as this is the time since midnight, and therefore will reset at this point.
Saving graphs can be achieved by using the dScope "export graph to file" method:
bRet = TraceWindow.TW_Export(CHANNEL_A, strAttachPath & strAttach(1)) |
Use it to save the required graphs to the attachment folder that is used by the script. Note that the graph exports should be in a format understood by browsers and email clients: .jpg and .gif have wide compatibility, .png slightly less so, particularly with older software. Avoid EMF, BMP and TIFF. If you need to keep local copies of the graphs, you may need to also save them with a unique file name (say made up of the date and time), otherwise they will get overwritten by the next graph export.
Notes and references
-
Microsoft CDO (Collaboration Data Objects): is an object library that exposes the interfaces of the Messaging Application Programming Interface (MAPI). However, instead of requiring C or C++ as MAPI does, CDO can be programmed using any development tool that creates COM objects, such as Active Server Pages (ASP), Microsoft® Visual Basic®, and Microsoft® Visual C++®.
CDO has had several incarnations, and previous versions shipped with different names and functionality. For example, in Microsoft® Exchange Server version 4.0, CDO was named OLE Messaging, and in Exchange Server 5.0, CDO was named Active Messaging. With the advent of Exchange Server version 5.5 and Microsoft® Outlook® 98, the library was renamed Collaboration Data Objects to describe its services better CDO provides much more than messaging functionality. Although the names have changed from version to version, any earlier applications using a previous version of CDO are compatible with the latest version of the library.
See http://msdn.microsoft.com/en-us/library/aa140862(office.10).aspx for more information or search the internet for "sending email with CDO". This is a common method of sending email from ASP servers and there is a lot of information out there including many tutorials and reference documents.
-
Third party SMTP server: - see softstack.com/freesmtp.html for one example that has apparently worked with Vista.
-
Emailing using CDO: See http://www.paulsadowski.com/WSH/cdo.htm
-
Coding HTML for emails: A good starting point would be http://www.sitepoint.com/article/code-html-email-newsletters - although this is for newsletters, the principles are identical. For emailing dScope results, it may be possible to code for a particular email client, but it's still best practice to make it as standards compliant and as widely compatible as possible, bearing in mind that it may be used to store the results for future reference which may be accessed from different email clients.
-
Configuring SMTP Servers: http://classicasp.aspfaq.com/email/how-do-i-send-e-mail-with-cdo.html has some useful information on what some of the error messages mean and links to further reference documents. http://www.paulsadowski.com/WSH/cdo.htm is a good reference with several worked examples of different configurations.