Please help to click 1!

Tuesday, 5 June 2012

Windows Script Host: Sending an Email Attachment with Microsoft Outlook


If Microsoft Office applications are installed on the target, they can be accessed via their COM automation interfaces. The example script below illustrates how Outlook can be used to email a file attachment. The script takes command line arguments for the recipient email address and the pathname of the file attachment. If Outlook is already running, the script gets a reference to its process and sends the email message. If it is not running, Outlook will be instantiated in a headless mode and it will send the message and terminate. In the latter case, the only visual indication a user would have that the Outlook was running would be a brief appearance of the Outlook icon in the system tray.
A169
4E46
' SendMailWithAttachment.vbs
' Uses Microsoft Outlook to create and send a message with a file attachment.
' The recipient's address and file are passed on the command line.
dim Args, Outlook, MAPI, RecipientAddress, Subject, Body, Message
dim FileSystemObject, AttachmentPathName, AttachmentName
if WScript.Arguments.Length <> 2 then
WScript.Echo "Usage: SendMailWithAttachment.vbs <Recipient Address> " + _
"<Attachment Absolute Pathname>"
WScript.Quit
end if
set Args = WScript.Arguments
RecipientAddress = Args.Item(0)
AttachmentPathName = Args.Item(1)
' Get a reference to Outlook if it is already running.
' If not, start it.
set Outlook = WScript.GetObject("", "Outlook.Application")
if Outlook is nothing then
WScript.Echo "Launching Outlook"
set Outlook = WScript.CreateObject("Outlook.Application")
else
WScript.Echo "Outlook was already running"
end if
set FileSystemObject = CreateObject("Scripting.FileSystemObject")
AttachmentName = FileSystemObject.GetFileName(AttachmentPathName)
Subject = "Testing Outlook script automation"
Body = "This is a test message from SendMailWithAttachment.vbs" + vbCrLf
set Outlook = WScript.CreateObject("Outlook.Application")
set MAPI = Outlook.GetNamespace("MAPI")
WScript.Echo "Generating message"
set Message = Outlook.CreateItem(olMailItem)
Message.Subject = Subject
Message.Body = Body
Message.To = RecipientAddress
WScript.Echo "Attaching file: " + AttachmentPathName
Message.Attachments.Add(AttachmentPathName).Displayname = AttachmentName
Message.Save
WScript.Echo "Sending message..."
Message.Send
WScript.Echo "Message sent"
set Outlook = nothing
set MAPI = nothing


Here is a sample invocation of the script and its output
D:\wsh>cscript SendMailWithAttachment.vbs aginos@webmd.net D:\wsh\test.txt
Microsoft (R) Windows Script Host Version 5.8
Copyright (C) Microsoft Corporation. All rights reserved.
Outlook was already running
Generating message
Attaching file: D:\wsh\test.txt

Sending message...
Message sent

No comments:

Post a Comment