I am creating an addon for Outlook 2007 that reads a mail item when it is received, and then rewrites it. The addon works great, and rewrites the mail for items that do not have
76mel's answer worked great! I am posting my resulting code just in case others want to do something similar (I'm new and not sure about the rules of posting lots of code, so sorry if it's against the rules):
private string getPRSearchKey(Outlook.MailItem m)
{
return m.PropertyAccessor.BinaryToString(m.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x300B0102"));
}
private void olApp_NewMail(string entryIDCollection)
{
Outlook.NameSpace outlookNS = this.Application.GetNamespace("MAPI");
Outlook.MAPIFolder mFolder = this.Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
Outlook.MailItem mail;
string pr_search_key;
string old_subj;
string old_body;
try
{
mail = (Outlook.MailItem)outlookNS.GetItemFromID(entryIDCollection, Type.Missing);
pr_search_key = getPRSearchKey(mail);
//save the pr_search_key, subject, and body before the mailItem gets moved
// then we can work on it without worrying about them disappearing
old_subj = mail.Subject;
old_body = mail.Body;
}
catch (Exception e) { Debug.WriteLine("exception with non-mail item " + entryIDCollection + ": " + e.ToString()); return; }
//
// ... do stuff with the mail's body and subject
//
try
{
mail.Subject = new_subj;
mail.Body = "";
mail.HTMLBody = text;
mail.ClearConversationIndex();
mail.Save();
}
catch (Exception ex)
{
//It wasn't caught in time, so we need to find the mail:
ArrayList unreadFolders = new ArrayList();
foreach (Outlook.Folder f in outlookNS.Folders) unreadFolders.Add(f);
while (unreadFolders.Count > 0)
{
Outlook.Folder currentFolder = unreadFolders[unreadFolders.Count-1] as Outlook.Folder;
Debug.WriteLine("reading folder: " + currentFolder.Name);
unreadFolders.RemoveAt(unreadFolders.Count - 1);
foreach (Outlook.Folder f in currentFolder.Folders) unreadFolders.Add(f);
try
{
Outlook.Items items = currentFolder.Items.Restrict("[UnRead] = true");
for (int itemNum = 1; itemNum <= items.Count; itemNum++)
{
if (!(items[itemNum] is Outlook.MailItem)) continue;
Outlook.MailItem m = items[itemNum];
if (getPRSearchKey(m) == pr_search_key)
{
m.Subject = new_subj;
m.Body = "";
m.HTMLBody = text;
m.ClearConversationIndex(); //don't think this works
m.Save();
return;
}
}
}
catch (Exception exc) { }
}
}
}
btw, something that I will probably change is I will skip querying certain folders to speed it up a bit (Journal, Deleted Items, Junk E-mail, Drafts, RSS Feeds, Microsoft at Home, Tasks, Notes, Contacts, Calendar, Sent Items, Outbox).