Extracting Attachment from Outlook Mail Item using C#

Here is an example C# code that helps you work on attachments in an outlook mail item. You can use Attachments property of Outlook MailItem object for saving attached file in outlook mail item by C# program. Refer to this post for more info about oMsg, Outlook MailItem object.

Below code snippet iterates to each mail in Inbox, checks the count of attachments in each mail item. If mail item attachment is not zero ie. Mail item has attachment, it iterates to each attachment in that mail item and then save the attachment at the specified location by using SaveAsFile() function.

foreach (Outlook.MailItem oMsg in oInbox.Items)
{

  if (oMsg.Attachments.Count!= 0)
  {
    for (int i = 1; i <= oMsg.Attachments.Count; i++)
    {
      string fn = oMsg.Attachments[i].FileName;
      oMsg.Attachments[i].SaveAsFile("D:/Outlook Download/" + fn);
    }
  }
}

If you want to download attachment of specific extension like .pdf, .docx, .xlsx etc. You can use below C# syntax for downloading attachment file with specific extension.

foreach (Outlook.MailItem oMsg in oInbox.Items)
{
  if (oMsg.Attachments.Count!= 0)
  {
    for (int i = 1; i <= oMsg.Attachments.Count; i++)
    {
      string fn = oMsg.Attachments[i].FileName;
      if (fn.ToUpper().EndsWith ("PDF"))
      {
        oMsg.Attachments[i].SaveAsFile("D:/Outlook Download/" + fn);
      }
    }
  }
}

Leave a Reply