Archive for category Scripts
Outlook Automation Error When Connecting From Elevated Prompt
One thing I didn’t realize until the other day is that a Vista command prompt that is elevated is unable to control Outlook. I was testing some JScript code from an elevated prompt and got this error:
Microsoft (R) Windows Script Host Version 5.7
Copyright (C) Microsoft Corporation. All rights reserved.
C:\Users\psheed\SendMail.js(1, 1) Microsoft JScript runtime error: Automation server can't create object
Unfortunately the error message isn’t very helpful in diagnosing the problem. After trying a few things I eventually found out that the script would work fine if it was running from a non-elevated prompt. Now it makes sense, you can’t use code that is running elevated to control non-elevated code for security reasons.
Automate the creation of an Outlook message with JScript
Every so often I need a way to automatically create an Outlook email message. I could create a C# application to do this but that is usually overkill and takes too much time to maintain the source and executable. Instead I create a simple JScript file that creates the Outlook message and populates it with the necessary information.
To do this create a new file named CreateMessage.js. Paste the code below into the file. Save the file and then at the command line run this command: “cscript CreateMessage.js”. Confirm the Outlook dialog that you want to do this and the new message will appear.
var outlookApp = new ActiveXObject("Outlook.Application");
var outlookNamespace =
outlookApp.GetNameSpace("MAPI").CurrentUser;
var mailItem = outlookApp.CreateItem(0);
var olTo = 1;
var olCC = 2;
var recipient = mailItem.Recipients.Add ("User1");
recipient.Type = olTo;
var recipient = mailItem.Recipients.Add ("User2");
recipient.Type = olCC;
mailItem.Subject = "Test Subject";
mailItem.HTMLBody = "Test Body";
mailItem.Display();
outlookNamespace.Logoff;