Search code examples
c#attachmentoutlook-addinmailitem

MailItem Attachments - Check if File Already Attached


I know how to add files to MailItem.Attachments but how do I check if the file is already added to Attachments?

For example, I have file name "C:\\myFolder\\myFile.txt". How do I check if this file is already attached or not? I need this to prevent double attaching a file to new email.

Here is what I have so far:

var mItem = Outlook.Interfaces.HostAddIn.Application.ActiveInspector().CurrentItem as MailItem;

if (mItem != null)
{
    //this works fine but I need to check if already attached first like below
    //mItem.Attachments.Add(localFilePath); 

    bool found = false;
    string attachments = "";
    for (int i = 1; i <= mItem.Attachments.Count; i++)
    {
        attachments += 
            "DisplayName: " + mItem.Attachments[i].DisplayName //shows just myFile.txt, no path
            + " / FileName: " + mItem.Attachments[i].FileName  //shows just myFile.txt, no path
            + " / PathName: " + mItem.Attachments[i].PathName; //shows ""

        //I tried here PathName, FileName, DisplayName but all return just name, without the path
        if (mItem.Attachments[i].PathName == localFilePath)
        {
            found = true;
        }
    }
    if (!found)
    {
        mItem.Attachments.Add(localFilePath); //attach only if not already attached
    }
}

Solution

  • What you have is pretty much the best you can do - FileName will match, PathName will always be empty, and DisplayName will be the same as FileName.

    You can also compare the old and existing file sizes, but do not use Attachment.Size as it includes the size of the MAPI specified properties plus the actual file data.

    Also don't forget to check that Attachmeent.Type == olByValue: you only want regular attachments.

    You can also (if the file name matches) save the existing attachment to a temp folder (Attachment.SaveAsFile) and compare file sizes. If they match, you can also compare the context (e.g. calculate a CRC).

    Note that you cannot access attachment data directly using OOM alone, you'd need Extended MAPI (IAttach::OpenProperty(PR_ATTACH_DATA_BIN, IID_IStream, ...)) or Redemption (I am its author - Attachment.AsText/AsArray/etc.). Otherwise you will need to use Attachment.SaveAsFile and then delete the temporary file.