I am currently trying to edit the html body of a mail item in the mailitem.open event. This works fine with rather short mails, but the longer the mail itself the more the screen flickers until it's loaded 100% by Outlook. What I try to do with this is imitating the Outlook default signature behavior, but with my own signature from a webservice.
The way I do this is first assigning an event to the itemload event:
Application.ItemLoad += new ApplicationEvents_11_ItemLoadEventHandler(Application_ItemLoad);
In the itemload method I assign the open event handler:
private void Application_ItemLoad(object item)
{
log.Debug("Application_ItemLoad");
if (item is MailItem)
{
var mailItem = (MailItem)item;
mailItem.Open += new ItemEvents_10_OpenEventHandler(MailItem_Open);
}
}
And finally in the mailitem.open event I am loading my signature into the mail
public void MailItem_Open(ref bool Cancel)
{
*some logic here to get the right mail*
{
LoadDefaultSignature(*the right mailitem*);
}
}
The LoadDefaultSignature then calls the webservice and places the signature at the right spot in the mail:
public void LoadDefaultSignature(MailItem mailItem)
{
try
{
log.Debug("LoadDefaultSignature");
var proxy = new WebServiceOutlookClient();
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var defaultSignature = proxy.GetDefaultSignatureByMail(Application.Session.CurrentUser.AddressEntry.GetExchangeUser().PrimarySmtpAddress);
if (defaultSignature != null)
{
var htmlDoc = GetHtmlDoc(mailItem);
*logic to place out text in original mail*
mailItem.HTMLBody = htmlDoc.DocumentNode.OuterHtml;
log.Debug("DefaultSignature set");
}
}
catch (System.Exception exc)
{
log.Error("Couldn't load default signature", exc);
}
}
I don't really understand why Outlook is showing this behaviour, as it is not doing it whenever I change the htmlbody later on from my custom task pane. Maybe there is some validation going on? I am also open for alternative ways to solve that. My idea was to maybe try the wordeditor and convert my html to openxml and use that but to no avail so far.
This is hardly surprising - you are resetting the whole document, so Outlook/Word need to reparse the whole message body: they are not sophisticated enough to figure out that only a part of it changed.
This is really a sledgehammer approach - if you are only changing parts of the body, use Word Object Model instead: use Inspector.WordEditor
or Explorer.ActiveInlineResponseWordEditor
(returns Document
object) depending on where the item is opened for editing. Once you know where the signature needs to be inserted, use Range.InsertFile
to insert you HTML data.