Monday, January 14, 2008 8:47 AM
jrupp
Office integration: easier than I thought
Friday morning, one of my co-workers idly remarked about something that occasionally happens to all of us -- we write an email and in some way reference a file we're intending to attach, but forget to attach the file. Especially if you're sending a build to a client and leaving for the day right away, this can be quite annoying. He rightly wondered aloud why Outlook doesn't warn you about that.
That evening on my train ride home, my mind wandered back to that comment, and I remembered that I installed the latest VSTO for Office 2007 a few weeks ago, so I thought I'd see how hard it would be to write an addon for Outlook that did just that. So, I fired up VS 2008 and created an Outlook Addin project, and got this:
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
After checking for instance variables, I noticed an 'Application' object. So, I checked it for events, and found an 'ItemSend'. A quick hook of the event (and unhook in the shutdown to be clean), and I had the ability to run my code when I wanted -- just before a message was sent. I added the checks and sure enough, I had a working version of the code in about 5 minutes.
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
this.Application.ItemSend += Application_ItemSend;
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
this.Application.ItemSend -= Application_ItemSend;
}
void Application_ItemSend(object Item, ref bool Cancel)
{
Outlook.MailItem mailItem = Item as Outlook.MailItem;
if (null != mailItem && mailItem.Attachments.Count == 0 && mailItem.Body.ToLower().Contains("attach")) {
if (MessageBox.Show("There are no attachments on this message and by the content of your message, it appears " +
"you may have intended to attach something. Are you sure you want to send this message?",
"Are you sure you want to send this message?",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2) == DialogResult.No)
{
Cancel = true;
}
}
}
Finally, something that was actually as simple to do as it seemed it should have been.