How to download attachments from outlook

How to download attachments from outlook

To download the attachments from your outlook inbox folder to a specific folder, you can use the code given below.

First, add assembly Microsoft.Office.Interlop.Outlook to the references of the C# project.

using Microsoft.Office.Interop.Outlook;

...

Application app = null;
_NameSpace ns = null;
MAPIFolder inboxFolder = null;

try
{
    app = new Application();
    ns = app.GetNamespace("MAPI");
    ns.Logon("Email", "Password", false, false);
    inboxFolder = ns.GetDefaultFolder(OlDefaultFolders.olFolderInbox);

    foreach (Object elem in inboxFolder.Items)
    {
        if (elem is MailItem)
        {
            MailItem item = (MailItem)elem;
            Console.WriteLine("Subject: " + item.Subject);

            var attachments = item.Attachments;
            int count = attachments.Count;
           

            for (int i = 1; i < count; ++i)
            {
                if (attachments[i] is Attachment)
                {
                    Attachment attachment = (Attachment)attachments[i];

                    Console.WriteLine("\tAttachment: " + attachment.FileName);
                    attachment.SaveAsFile(@"D:\SaveFolder\" + attachment.FileName);
                }
            }
        }
    }
}
catch (System.Runtime.InteropServices.COMException ex)
{
    Console.WriteLine(ex.ToString());
}
finally
{
    ns = null;
    app = null;
    inboxFolder = null;
}

 


added 5 years 2 months ago

- A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.ServiceModel.dll
- A first chance exception of type 'System.ServiceModel. CommunicationObjectAbortedException' occurred in System.ServiceModel.dll
- System.AccessViolationException: Attempted to read or write protected memory
- How to download attachments from outlook
- How to add Startup items to Windows 8
- How to forward IP-Port on Windows Machine
- There's more than one way to do it (TMTOWTDI)
- Don't repeat yourself (DRY)