Outlook 2010: How to compose e-mail from VBScript/JScript - javascript

I have some JScript code I have been using for a few years which is able to read an XML file and open an Outlook compose window with the to/cc/subject fields prepopulated and files pre-attached based on the XML data. The user can then attach more files, make any corrections and send the e-mail. The core part of the code uses CDO to create the new message:
var ol = WScript.CreateObject("Outlook.Application");
var msg = ol.CreateItem(olMailItem);
Unfortunately I have just discovered this no longer works with Outlook 2010 64-bit as CDO is no longer supported. The suggestion from Microsoft is to update your applications to use the Outlook object model instead, but I can't find any examples at all of how I might use the Outlook object model to open a compose window from either VBScript or JScript. All the "VB" examples on MSDN produce syntax errors when run through the VBScript interpreter.
Can anyone point me to any short examples demonstrating how to interface with Outlook 2010 using either VBScript or JScript?
EDIT: Just realised the problem is that I'm using MAPI.Session to adjust attachment properties and this is what's failing. I guess I need to find what this has been replaced by:
var oSession = WScript.CreateObject("MAPI.Session");
oSession.Logon("", "", false, false);
var oMsg = oSession.GetMessage(strMsgID);
var oAttachFields = oMsg.Attachments.Item(i+1).Fields;
...

Ok, turns out most of the MAPI.Session stuff has been merged in with the actual objects, which are still accessible using the first bit of code in my post ("Outlook.Application"). I was only using the MAPI.Session stuff to hide image attachments (so they can be shown inline in the message body, and not as files attached to the e-mail) but this now seems to be incorporated automatically.
So all I actually had to do was remove the MAPI.Session stuff and then everything started working. I will post a link to the code shortly in case anyone else finds it useful.
EDIT: Here is the code on GitHub if anyone is after a relatively simple example.

Related

Kotlin, how can I read a dynamic website as text?

As titled, I'm trying to read the content of sites like this one, which appears to be javascript based.
I tried using plain jdk lib, then jsoup and then htmlunit, but I couldn't get anything useful out of it (I see just the source code or just the title or null):
val url = URL("https://registry.terraform.io/providers/hashicorp/tls/latest/docs/data-sources/certificate")
val connection = url.openConnection()
val scanner = Scanner(connection.getInputStream())
scanner.useDelimiter("\\Z")
val content = scanner.next()
scanner.close()
println(content)
val doc = Jsoup.connect("https://registry.terraform.io/providers/hashicorp/tls/latest/docs/data-sources/certificate").get()
println(doc.text())
WebClient().use { webClient ->
val page = webClient.getPage<HtmlPage>("https://registry.terraform.io/providers/hashicorp/tls/latest/docs/data-sources/certificate")
val pageAsText = page.asNormalizedText()
println(pageAsText)
}
WebClient(BrowserVersion.FIREFOX).use { webClient ->
val page = webClient.getPage<HtmlPage>("https://registry.terraform.io/providers/hashicorp/tls/latest/docs/data-sources/certificate")
println(page.textContent)
}
It should be something easy peasy, but I cant see what's wrong
In order for this to be possible, you need something to execute the JS that modifies the DOM.
It might be a bit overkill depending on the use case, and probably won't be possible if you're on Android, but one way to do this is to launch a headless browser separately and interact with it from your code. For instance, using Chrome Headless and the Chrome DevTools Protocol. If you're interested, I have written a Kotlin library called chrome-devtools-kotlin to interact with a Chrome browser in a type-safe way.
There might be simpler options, though. For instance maybe you can run an embedded browser instead with JBrowserDriver and still use JSoup to parse the HTML, as mentioned in this other answer.
Regarding HtmlUnit:
the page has initially no content, all you see is rendered from javascript magic on the client side using one of this spa frameworks.
It looks like there is some feature check in the beginning that figures out the js support in HtmlUnit does not have all the required features and based on this you only get a hint like "Please enable Javascript to use this application".
You can use
page.asXml()
to have a look at the content trough HtmlUnit's eyes.
You can open an HtmlUnit issue on github but i fear adding support for this will be a longer story.

How to use FileSystemObject to read file in JavaScript

I want to read a file with FileSystemObject. My code is as following:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Read json</title>
</head>
<body>
<script type="text/javascript">
function readFile(filename){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var ForReading = 1;
var f1 = fso.OpenTextFile(filename, ForReading);
var text = f1.ReadAll();
f1.close();
return text;
}
myJSONText = "text.txt";
var myObject = readFile(myJSONText);//eval('(' + myJSONText + ')');
document.write(myObject.name);
</script>
</body>
</html>
First, let me repeat some comments above. I've never seen using ActiveXObject client side extolled as a thing that should be done.
Now, let me say I'm trying to learn how to do this myself. Here are some thoughts (and helpful links, see the bottom) on this question.
The general layout, according to "Much ADO about Text Files" on MSDN's scripting clinic column, is:
Create the object.
Create another object, using the first, that uses
a method of the first object (such as getting a file).
Do things to
the file.
Close the file.
How do you start? According to IE Dev Center (linked here), use an ActiveXObject in Javascript as follows:
newObj = new ActiveXObject(servername.typename[, location])
You've got that when you declare fso in your code. What about this "servername" thing, isn't the file accessed locally? Instead of "servername etc" you've put in Scripting.FileSystemObject. This is actually fine, if the HKEY_CLASSES_ROOT registry key on the host PC supports it (see ref above).
Once the ActiveXObject is successfully declared, and if the browser allows it (IE only), and if the end user agrees to any warnings that pop up ("An ActiveX control on this page might be unsafe to interact with other parts of the page..." etc), then the object allows you to use any of the methods associated with that object. That's where the power of the Windows Scripting FileSystemObject comes into play.
Any FileSystemObject (fso) method is now available to use, which as its name suggests, means file (and directory) interaction on the local machine. Not just reading, as your question is focused on, but writing and deleting as well. A complete list of methods and properties is available at MSDN here. After being used, close out the file using the .close() method.
So, this is dangerous for obvious reasons. But what wasn't obvious to me at first was that these interactions with the filesystem may happen invisibly. There is a good chance that whatever you do, from reading a file to deleting a directory tree, no warnings or command prompts will come up to let you know what's happening because of your few lines of code.
Let me finish by commenting on the last bits of code above. Using JSON in conjunction with data pulled from the FileSystemObject provides a great way to allow JavaScript interaction (JSON .parse and .stringify come immediately to mind). With this, data could be stored locally, perhaps as an alternative to HTML5 local storage (ref this SO thread, which goes more in-depth with this concept, and another SO question I raised about this here).
Here are some links for further reading:
IE Dev Center, JavaScript Objects, ActiveXObject
MSDN JScript Windows Scripting (including FileSystemObject methods, etc)
MSDN Scripting Clinic (older articles, many broken links, but stil a lot of good info on this stuff)

Using JavaScript to "Create" a Microsoft Word Document

I would like to dynamically create a document using JavaScript and then open that document in Microsoft word. Is this possible? Here is my current code:
<html>
<head>
<title></title>
<script src="js/jquery-1.4.4.js" type="text/javascript"></script>
</head>
<body>
<div id="myDiv">The quick brown fox jumped lazly over the dead log.</div>
<script type="text/jscript">
var printWindow = window.open("", "Print", "width=800,height=400,scrollbar=0");
var printAreaHtml = $("#myDiv").attr("outerHTML");
printWindow.document.open("text/html", "replace");
printWindow.document.writeln("<html><head>")
printWindow.document.writeln("<meta HTTP-EQUIV='Content-Type' content='application/vnd.ms-word'>");
printWindow.document.writeln("<meta HTTP-EQUIV='Content-Disposition' content='attachment;filename=print.doc'>");
printWindow.document.writeln("</head>");
printWindow.document.writeln("<body>");
printWindow.document.write(printAreaHtml);
printWindow.document.writeln("</body>");
printWindow.document.writeln("</html>");
printWindow.document.close();
// printWindow.print();
</script>
</body>
</html>
I'm not sure exactly what you are trying to do in your code up there but here is some information i found about accessing a word document and a table within the doc:
Microsoft Word Object Model
This object model is part of Microsoft Word (not Javascript) and it lets you "automate" word remotely from other programs (not just web pages, but any computer program).
It is primarily designed for Visual Basic, but can be accessed by Javascript from a web page - see para 2 below.
However it is a bit more tricky to use through Javascript, particularly because you cannot use visual basic constants - you need to refer to them by value. If you research this further, you will soon know what I mean by this.
So where can you find out about this Object Model?
It is all there in the Word help files if you look for it.
If you look in the Word help, under programming information, you will find the Microsoft Word Visual Basic Programming Reference.
The Word object model, which lets you do things you will need to solve your problem like:
Open Word
Open a Document in Word
Access the collection of Tables in that ActiveDocument.
Access the Rows and Cells of a given Table.
How do you access this from Javascript?
This might only be done I think through Internet Explorer (and perhaps Opera).
Here you need to learn about ActiveXObjects.
ActiveXObjects (if you do not know) are separate computer programs which enable additional functionality. There are lots of ActiveX objects on the internet.
When you install Word, this also installs an ActiveX object for automating word, giving you access to the Word Object Model.
So in javascript, lets open up a new instance of word:
var oApplication=new ActiveXObject("Word.Application");
oApplication.Visible=true; // "Visible" is in the Word Object Model`
There you have it.
Then if you want to open you file and get the table:
oApplication.Documents.Open("myfilename");
var oDocument=oApplication.ActiveDocument;
var oTable=oDocument.Tables(1);`
And now I leave it to you to keep going with the rest.
EDIT: this wasn't possible when the question was asked but in 2017 it is. See link from comment by jrm - http://www.effectiveui.com/blog/2015/02/23/generating-a-downloadable-word-document-in-the-browser/
Browser place some serious restrictions on Javascript which will prevent you creating a downloadable file. See this related question:
Create a file in memory for user to download, not through server
I don't believe that this idea will work. You need to create the Word file with a serverside language. For example PHP: http://www.webcheatsheet.com/php/create_word_excel_csv_files_with_php.php
You can not get this working using client side. Main thing is you need to send headers not as html. So I would suggest you to use server side scripting as Max suggested and preferably use .htaccess file if you are using Apache server to also name these files as .doc.
Lets assume your php file needs to create a .doc file with some passed argument lets say id. So you want file_.doc to point to file.php?id=, try using following rewrite rule so that browser understands by extension too
RewriteRule file_(.*).doc file.php?id=$1
if you need server side document generation and server is running Java, take a look at this:
https://github.com/leonardoanalista/java2word/
This is absolutely possible. Googoose is a jQuery plugin that I wrote to handle a lot of the more complicated conversions. It's still fairly new, but there appear to be a few other attempts at this, so you could check those out. Here is the best documentation I've found so far that actually explains this process http://sebsauvage.net/wiki/doku.php?id=word_document_generation. If you're interested check out the examples in Googoose.
sometimes we can not use server side app or activeX to create office document because of phonegap mobile app that uses only client-side javascipt to operate.
the only way i found for now is uding word binary file format or OOXML
http://msdn.microsoft.com/en-us/library/hh643138(v=office.12)
some say that its much easier to create RTF file and i agree with them.

Getting URL of executing JavaScript file (IE6-7 problem mostly)

Hey all, I've been trying to throw together a generic function that retrieves the absolute URL of an executing JavaScript file on a web page:
http://gist.github.com/433486
Basically you get to call something like this:
getScriptName(function(url) {
console.log(url);
// http://www.example.com/myExternalJsFile.js
});
inside an external JavaScript file on a page and can then do something with it (like find the <script> tag that loaded it for example).
It works great in almost all the browsers I've tested (Firefox, Chrome, Safari, Opera v10 at least, and IE 8).
It seems to fail, however, in IE 6 and 7. The callback function gets executed, but the retrieved name is the URL to the main HTML page, not the JavaScript file. Continuing with the example, getScriptName invokes the callback with the parameter: http://www.example.com/index.html
So all I'm really asking is if there's some other way of getting the URL of the current JavaScript file (which could be IE 6 and 7 specific hackery)? Thanks in advance!
EDIT: Also, this won't work in every case, so please don't recommend it:
var scripts = document.getElementsByTagName("script");
return scripts[scripts.length-1].src;
I'd like it to work in the case of dynamically created script tags (possibly not placed last in the page), aka lazy-loading.
A lot of this depends on what you have access to. If, as it appears, you are trying to do this entirely within the JS code, I do not believe that you are able to do it, for some of the reasons shown above. You could get 90% of the way maybe, but not be definitive.
If you are working in a dotnet environment ( which is the only one I know ), I would suggest the use of a module that would intercept all JS requests and add into them the request location, or something of that nature.
I think you need to address this from the server side, not the client side. I do not think you will have a definitive answer form the client side. I think you will also struggle to get an answer from the server side, but you might be more successfull.
Sorry, I suspect you might struggle with this. IE earlier than version 8 typically gives error messages from javascript errors of the form:
line: 342
char: 3
error: expected identifier, string or number
code: 0
url: http://example.com/path/to/resource
where the url is the window.location.href, rather than the URL of the external Javascript resource that contains the problem. I suggest that IE gives the unhelpful URL value since the script URL isn't available to IE at that point, and neither is it available to any Javascript you might write to try to display it.
I would love to be able to link to IE8 release notes which say this bug / feature has been fixed, hence the reason I created this as community wiki. My MSDN foo is pretty weak!

Tutorial for using JavaScript on a Desktop

I need to do some scripts in java script.
I am working on it but couldn't find a few solutions to a few problems.
First of all I need a GOOD tutorial, but not for an internet page but for a DESKTOP script.
Things couldn't find out like :
1) I wanted a simple message box in order to debug my program, I used:
var name = prompt("What is your name","Type Name Here");
When running it I get error of "Object expected"
2) Couldn't find how to open a file
Based on your comments, I guess that you are attempting to run a JavaScript file directly on Windows. Double-clicking on a .js file in windows will (probably) run it in Windows Script Host.
The prompt() function will not work this way, since WSH provides a completely different API than browser-embedded engines.
The following code should accomplish your intentions. However if you want anything more than a simple popup, HTAs are the only way to do complex GUIs with JScript on the desktop.
var fso, ws, ts;
fso = new ActiveXObject('Scripting.FileSystemObject');
ws = WScript.CreateObject('WScript.Shell');
var ForWriting= 2;
ts = fso.OpenTextFile('foo.txt', ForWriting, true);
ts.WriteLine(new Date().getTime());
ts.Close();
ws.Popup('Wrote to file!');
var ForReading= 1;
ts = fso.OpenTextFile('foo.txt', ForReading, false);
var fileContents = ts.ReadLine();
ts.Close();
ws.Popup('The file contained: ' + fileContents);
WScript.Quit();
I have to ask: why is JavaScript the right tool for the job? Why not use a scripting language intended to be used this way, such as Python, Ruby, Lua, ... etc?
If you are using Microsoft's JScript (and it sounds like you are), look to the MSDN web site for help. The page here looks fairly good. Google can also help with that.
Assuming you don't mind using Java, you could also use the Mozilla Rhino shell. But it doesn't look like there is a standard way of reading from the console in JavaScript. (presumably since this is not something typically required in a JavaScript application...) The built in JavaScript functions in the shell seem fairly basic, but you can read a file.
There area also examples of using Rhino, which may be helpful. You can interface with the Java API to do whatever else you need to do.
Edit: I wrote this answer a long time ago; today I would use node.js. See their learning page.
The latest prerelease of Opera acts as a runtime for JS applications.
They have tutorials describing how to use it.
I used: var name = prompt("What is your name","Type Name Here");
When running it I get error of "Object expected"
Presumably your runtime doesn't implement prompt that in a way that is compatible with those arguments.
2) Couldn't find how to open a file
This depends on the runtime you use. JS itself doesn't have anything built in to read files (or display a prompt). You need an environment that provides those objects.

Categories

Resources