I have an application with a document management element, part of this element is an Outlook Addin which allows the saving of emails into a server location and updates my applications database.
When the user selects to save the email they are presented with a windows form where they enter extra detail before the email is saved. Intermittently they are receiving an "Operation Failed" error when the code attempts to use the MailItem.SaveAs() method, once the error occurs any further attempt to save emails will throw the same exception.
If the user restarts Outlook and attempts to save the same email again it will, mostly, succeed.
User are experiencing this error on a variety of Operating Systems and versions of Office (2010 and above), nothing unusual about usernames or profile settings.
Any guidance would be very gratefully received.
What I have tried:
The online investigations I have undertaken indicate that this tends to be a problem with file paths or filenames containing invalid characters, based on this I have altered the original code to ensure that the filenames can only contain alpha and numeric characters. The files are saved to the users local temp directory before being moved to the server.
The method used to save the email can be seen below.
The fileName parameter is Guid.NewGuid().ToString().Replace("-","")+".msg", the includeAttachments parameter is always set to True. The Outlook.MailItem is passed into the class constructor and assigned to the mailItem variable.
public void Save(string fileName, bool includeAttachments)
{
if (string.IsNullOrWhiteSpace(fileName))
throw new ArgumentNullException(fileName);
if (this.mailItem == null)
return;
try
{
if (includeAttachments)
{
this.mailItem.SaveAs(fileName, 3); <--- This line throws the "Operation Failed" exception
return;
}
var mailItemCopy = new MailItem(this.mailItem.Copy());
mailItemCopy.RemoveAttachments();
mailItemCopy.Item.SaveAs(fileName, 3);
mailItemCopy.Item.Close(Outlook.OlInspectorClose.olDiscard);
mailItemCopy.Item.Move(mailItemCopy.Item.Application.GetNamespace("MAPI").GetDefaultFolder(Outlook.OlDefaultFolders.olFolderDeletedItems));
}
catch (Exception ex)
{
throw new Exception(ex.Message + "(FileName:" + fileName + "; IncludeAttachments:" + includeAttachments.ToString());
}
}