A small set of classes to interact with Outlook via COM dynamically without referencing the Office assemblies.
I've been playing around on a small project experiment, and found myself wanting to programmatically send emails. I didn't want to have to worry about using my own SMTP server and credentials, so naturally I wanted to use whatever the user had installed, if at all possible.
This being a Windows project for the office worker, quite a large portion of my target audience would have Outlook installed. Web-based mailing systems have been growing in popularity for sure but I'm not certain how I would go about sending emails transparently using those. Maybe something to try out later on. Anyways I settled on using Outlook.
All Office apps have an object model exposed via COM, which can be used from managed code via the PIA. This has the advantage of exposing data types (for strong typing) and making things like IntelliSense work in Visual Studio. But it means shipping an extra DLL and takes some of the fun away so instead I decided to use the IDispatch automation interface exposed by Outlook for VBA projects and late-bind at runtime.
I'd already done something like that years ago for an assignment when I worked at Barclays in London, but found that .Net 4.0 has a much, much easier way to do it now. They introduced the dynamic keyword that actually does all the tedious work of discovering method and property signatures. i.e., the compiler will let you call methods it doesn't know actually exist on dynamic variables. That's pretty cool! Note that this is very different from the var keyword, which does enforce type safety at compile time and is just syntactic sugar.
// No idea what datatype "Recipients" is at compile time
dynamic recipients = myMailItem.Recipients;
// We'll figure out whether Add() exists and what its arguments are at runtime
recipients.Add("joe@schmoe.com");
Of course, I should point out that the resulting code is slower than if I had hand-coded the IDispatch invocations (I would have probably "assumed" the methods I knew to be there would be there), but for my quick and dirty project it was plenty fast and made my life much simpler.
The classes can be used to:
Some notes: