none
Download Attachments by Clicking a Button RRS feed

  • Question

  • Hello Outlook Experts!  About 3 weeks ago I found some C# code online that was supposed to download attachments from Outlook.  I tried the sample code; it didn't work.  I made some basic modifications; still didn't work.  I posted a question about downloading attachments, using C#, in the C# forum.  Here is my original post:

    http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/8d7a7245-76f3-4fbe-8e1a-fa7517829c7c/

    I seemed to make a little progress, going forward, and then seemed to go backward.  Eventually, Yoyo Jiang posted some sample code that seemed like it should have worked.  Here is the sample code:

    https://skydrive.live.com/?cid=37142ebae462f7f1&id=37142EBAE462F7F1!137

    The file to download is named 'TestSaveEmailAttachments'.  I downloaded this project, and ran the code, but still couldn't get C# to download attachments. 

    Can someone here follow the thread and figure this out?  I'd love to see this working, and get back to Michael Sun with a working solution.

    Thanks!!


    Ryan Shuell

    Wednesday, April 11, 2012 3:35 AM

Answers

  • Open up outlook normally and show us screenshot of navigation pane (where you have tree structure of your folders and accounts)

    • Marked as answer by ryguy72 Wednesday, April 11, 2012 10:22 PM
    Wednesday, April 11, 2012 8:56 AM
  • that is exactly the problem you have - original code from that other thread assumed that forst store is the one that holds your emails. So in original code replace your line:

    oNS.GetDefaultFolder (olFolderInbox)

    with something like that:

    Store myStore = null;

    for(int i=1; i <= oNS.Stores.Count; i++)

    {

    if(oNS.Stores[i].DisplayName == "ryanshuell@gmail.com")

    {

    myStore = oNS.Stores[i];

    break;

    }

    }

    MAPIFolder inbox = myStore.GetDefaultFolder(olFolderInbox)

    and all other things are without changes. Of course i assume that you want to process mails from gmail account.

    • Marked as answer by ryguy72 Wednesday, April 11, 2012 10:21 PM
    Wednesday, April 11, 2012 2:39 PM
  • you need to adapt sample code i gave you to fit into your existing function - you already have variable 'i' declared so use other name in looping through stores. And instead of olFolderInbox use Outlook.OlDefaultFolders.olFolderInbox. Also line below should be inbox.Items and not oInbox.Items.

    • Marked as answer by ryguy72 Wednesday, April 11, 2012 10:21 PM
    Wednesday, April 11, 2012 8:20 PM

All replies

  • Open up outlook normally and show us screenshot of navigation pane (where you have tree structure of your folders and accounts)

    • Marked as answer by ryguy72 Wednesday, April 11, 2012 10:22 PM
    Wednesday, April 11, 2012 8:56 AM
  • This is it:


    Ryan Shuell

    Wednesday, April 11, 2012 2:17 PM
  • that is exactly the problem you have - original code from that other thread assumed that forst store is the one that holds your emails. So in original code replace your line:

    oNS.GetDefaultFolder (olFolderInbox)

    with something like that:

    Store myStore = null;

    for(int i=1; i <= oNS.Stores.Count; i++)

    {

    if(oNS.Stores[i].DisplayName == "ryanshuell@gmail.com")

    {

    myStore = oNS.Stores[i];

    break;

    }

    }

    MAPIFolder inbox = myStore.GetDefaultFolder(olFolderInbox)

    and all other things are without changes. Of course i assume that you want to process mails from gmail account.

    • Marked as answer by ryguy72 Wednesday, April 11, 2012 10:21 PM
    Wednesday, April 11, 2012 2:39 PM
  • OK!!  I knew it had to do with the Inbox, which was never evaluated.  Somehow, this still is NOT working.  Here is my code now:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    //using Outlook = Microsoft.Office.Interop.Outlook;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Diagnostics;
    using System.Reflection;
    using Microsoft.Office.Interop.Outlook;


    namespace TestSaveEmailAttachments
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            private void button1_Click(object sender, EventArgs e)
            {
                // Or This Way:
                Microsoft.Office.Interop.Outlook.Application oApp = Marshal.GetActiveObject("Outlook.Application") as Microsoft.Office.Interop.Outlook.Application;

                    //Outlook.Application application = null;
                    //Outlook.NameSpace nameSpace = null;

                    //// Check if there is an Outlook process running.
                    //if (Process.GetProcessesByName("OUTLOOK").Count() > 0)
                    //{
                    //    // If so, use the GetActiveObject method to obtain the process and cast it to an Application object.
                    //    application = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
                    //}
                    //else
                    //{
                    //    // If not, create a new instance of Outlook and log on to the default profile.
                    //    application = new Outlook.Application();
                    //    nameSpace = application.GetNamespace("MAPI");
                    //    nameSpace.Logon("", "", Missing.Value, Missing.Value);
                    //    nameSpace = null;
                    //}

                    //if (nameSpace == null)
                    //{
                    //    nameSpace = application.GetNamespace("MAPI");
                    //}

                    //Outlook.MAPIFolder inbox = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
                    //string account = inbox.FolderPath;


                //Outlook._Application oApp = new Outlook.Application();
                Microsoft.Office.Interop.Outlook.NameSpace oNS = oApp.GetNamespace("mapi");
                oNS.Logon("LatestProfile");

                //Outlook.MAPIFolder oInbox = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
                
                Store myStore = null;

                    for(int i=1; i <= oNS.Stores.Count; i++)
                    {
                    if(oNS.Stores[i].DisplayName == "ryanshuell@gmail.com")
                        {
                        myStore = oNS.Stores[i];
                        break;
                        }
                    }
                MAPIFolder inbox = myStore.GetDefaultFolder(olFolderInbox);

                Microsoft.Office.Interop.Outlook.Items oItems = oInbox.Items;
                int i = 0;
                foreach(var oMail in oItems)
                {
                    if (oMail is Microsoft.Office.Interop.Outlook.MailItem)
                    {
                        if (i < 20)
                        {
                            i++;
                            SaveMailAttachments(oMail as Microsoft.Office.Interop.Outlook.MailItem);
                        }
                        else
                        {
                            break;
                        }
                    }
                }

                MessageBox.Show("Done");

            }

            private void SaveMailAttachments(Microsoft.Office.Interop.Outlook.MailItem mailItem)
            {
                Microsoft.Office.Interop.Outlook.Attachments attachments = mailItem.Attachments;
                    if (attachments != null && attachments.Count > 0)
                    {
                        for (int i = 1; i <= attachments.Count; i++)
                        {
                            Microsoft.Office.Interop.Outlook.Attachment attachment = attachments[i];
                            if (attachment.Type == Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue)
                            {
                                string filename = Path.Combine(@"C:\Users\Excel\Desktop\Outlook_Attachments\", attachment.FileName);
                                attachment.SaveAsFile(filename);
                            }
                        }
                    }
            }
                   
        }
    }

    Here are my 3 errors:

    Error    3    A local variable named 'i' cannot be declared in this scope because it would give a different meaning to 'i', which is already used in a 'child' scope to denote something else    C:\Users\Excel\Desktop\TestSaveEmailAttachments\TestSaveEmailAttachments\Form1.cs    77    17    TestSaveEmailAttachments
    Error    2    The name 'oInbox' does not exist in the current context    C:\Users\Excel\Desktop\TestSaveEmailAttachments\TestSaveEmailAttachments\Form1.cs    76    61    TestSaveEmailAttachments
    Error    1    The name 'olFolderInbox' does not exist in the current context    C:\Users\Excel\Desktop\TestSaveEmailAttachments\TestSaveEmailAttachments\Form1.cs    74    57    TestSaveEmailAttachments

    What is wrong now?

    ScreenShot:


    Ryan Shuell



    • Edited by ryguy72 Wednesday, April 11, 2012 3:55 PM
    Wednesday, April 11, 2012 3:54 PM
  • you need to adapt sample code i gave you to fit into your existing function - you already have variable 'i' declared so use other name in looping through stores. And instead of olFolderInbox use Outlook.OlDefaultFolders.olFolderInbox. Also line below should be inbox.Items and not oInbox.Items.

    • Marked as answer by ryguy72 Wednesday, April 11, 2012 10:21 PM
    Wednesday, April 11, 2012 8:20 PM
  • Ah!  Yes!  That [i] to [j] was silly.  I’ve been working on this for so long I totally missed that easy one.  Not sure I would have gotten those other two things myself.  If you have some spare time in the next couple of days, can you please tell me how you figured it out.  I know some C#; trying to learn it a lot better.  I’d love to know the logic behind this.  I’d love to know how you thought of checking for the Display Name.  How did you know it was: oNS.Stores[k].DisplayName

    For the benefit of others who encounter this challenge someday, and stumble across this discussion, here is the code in it's entirety:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Diagnostics;
    using System.Reflection;
    using Microsoft.Office.Interop.Outlook;


    namespace TestSaveEmailAttachments
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            private void button1_Click(object sender, EventArgs e)
            {
                // Or This Way:
                Microsoft.Office.Interop.Outlook.Application oApp = Marshal.GetActiveObject("Outlook.Application") as Microsoft.Office.Interop.Outlook.Application;


                //Outlook._Application oApp = new Outlook.Application();
                Microsoft.Office.Interop.Outlook.NameSpace oNS = oApp.GetNamespace("mapi");
                oNS.Logon("LatestProfile");

                //Outlook.MAPIFolder oInbox = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
                
                Store myStore = null;

                    for(int k=1; k <= oNS.Stores.Count; k++)
                    {
                    if(oNS.Stores[k].DisplayName == "ryanshuell@gmail.com")
                        {
                        myStore = oNS.Stores[k];
                        break;
                        }
                    }
                    MAPIFolder inbox = myStore.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);

                Microsoft.Office.Interop.Outlook.Items oItems = inbox.Items;
                int j = 0;
                foreach(var oMail in oItems)
                {
                    if (oMail is Microsoft.Office.Interop.Outlook.MailItem)
                    {
                        if (j < 20)
                        {
                            j++;
                            SaveMailAttachments(oMail as Microsoft.Office.Interop.Outlook.MailItem);
                        }
                        else
                        {
                            break;
                        }
                    }
                }

                MessageBox.Show("Done");

            }

            private void SaveMailAttachments(Microsoft.Office.Interop.Outlook.MailItem mailItem)
            {
                Microsoft.Office.Interop.Outlook.Attachments attachments = mailItem.Attachments;
                    if (attachments != null && attachments.Count > 0)
                    {
                        for (int i = 1; i <= attachments.Count; i++)
                        {
                            Microsoft.Office.Interop.Outlook.Attachment attachment = attachments[i];
                            if (attachment.Type == Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue)
                            {
                                string filename = Path.Combine(@"C:\Users\Excel\Desktop\Outlook_Attachments\", attachment.FileName);
                                attachment.SaveAsFile(filename);
                            }
                        }
                    }
            }
                   
        }
    }


    Again, thanks for your help with this!  

    Ryan Shuell

    Wednesday, April 11, 2012 10:21 PM
  • that is exactly the problem you have - original code from that other thread assumed that forst store is the one that holds your emails. So in original code replace your line:

    oNS.GetDefaultFolder (olFolderInbox)

    with something like that:

    Store myStore = null;

    for(int i=1; i <= oNS.Stores.Count; i++)

    {

    if(oNS.Stores[i].DisplayName == "email")

    {

    myStore = oNS.Stores[i];

    break;

    }

    }

    MAPIFolder inbox = myStore.GetDefaultFolder(olFolderInbox)

    and all other things are without changes. Of course i assume that you want to process mails from gmail account.

    MAPIFolder inbox = myStore.GetDefaultFolder(olFolderInbox) i am getting error at this line plz help me
    Thursday, December 13, 2012 11:37 AM
  • what error exactly? and please do not attach your questions to long forgotten threads, especially when your problems are not the same as for original author's.
    Thursday, December 13, 2012 11:45 AM
  • what error exactly? and please do not attach your questions to long forgotten threads, especially when your problems are not the same as for original author's.

    i want to store outlook2010 attachments into local folder.but while i am using 2007 my code is working properly

    but in outllok 2010 i amnot able to get the gmail attachments becoz it saving in another inbox plz help with u r code?

    Friday, December 14, 2012 6:21 AM
  • iterate through stores untill you find the one for gmail (checking its name) and obtain folder from it. What seems to be the problem? maybe show us your code

    Friday, December 14, 2012 7:37 AM
  • iterate through stores untill you find the one for gmail (checking its name) and obtain folder from it. What seems to be the problem? maybe show us your code

    const string destinationDirectory = @"C:\TestFileSave";

                if (!Directory.Exists(destinationDirectory))
                {
                    Directory.CreateDirectory(destinationDirectory);
                }

                MAPIFolder sentMail = Application.ActiveExplorer().Session.GetDefaultFolder(OlDefaultFolders.olFolderSentMail);
                Items sentMailItems = sentMail.Items;
                try
                {
                    foreach (object collectionItem in sentMailItems)
                    {
                        MailItem newEmail = collectionItem as MailItem;
                        if (newEmail == null) continue;

                        if (newEmail.Attachments.Count > 0)
                        {
                            for (int i = 1; i <= newEmail.Attachments.Count; i++)
                            {
                                string filePath = Path.Combine(destinationDirectory, newEmail.Attachments[i].FileName);
                                newEmail.Attachments[i].SaveAsFile(filePath);
                            }
                        }
                    }
                }
                catch (SystemException ex)
                {
                    string s= ex.Message;
                    MessageBox.Show(s);

                }

            }

    THIS IS MY CODE BUT IT'S FOR OUTLLOK 2007.BUT I NED ACCESS GMAIL IN THE OUTLLOK SO PLZ HELP ME WITH U R CODE

                             
    Friday, December 14, 2012 7:45 AM
  • iterate through stores untill you find the one for gmail (checking its name) and obtain folder from it. What seems to be the problem? maybe show us your code

    PLZ SHARE ANY WORKING SAMPLE ON SKY DRIV
    Friday, December 14, 2012 7:47 AM
  • if you want working code, there are sites like odesk.com where you can request working apps for money. Here you will get hints and nudges but work to be done is all yours.

    change line

    MAPIFolder sentMail = Application.ActiveExplorer().Session.GetDefaultFolder(OlDefaultFolders.olFolderSentMail);

    to something like this:

    sentMail = GetSentFolderFromGmailStore();

    function GetSentFolderFromGmailStore()

    {

    foreach(Store store in Application.Session.Stores)

    {

    if(store.DisplayName == "your gmail account")

    return store.GetDefaultFolder(OlDefaultFolders.olFolderSentMail);

    }

    }


    • Edited by DamianD Friday, December 14, 2012 5:59 PM error in pseudocode
    Friday, December 14, 2012 8:56 AM