none
Download Attachments by Clicking a Button

    Question

  • I found some code on the discussion forums.  It is supposed to download attachments from Outlook, into a folder.  I’m trying to run the code by clicking a Button on a Form.  I can’t seem to get the button_Click event to the fire the code.  This is what I have 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 Microsoft.Office.Interop.Outlook;

    using System.IO;

     

     

    namespace WindowsFormsApplication6

    {

        publicpartialclassForm1: Form

        {

            publicForm1()

            {

                InitializeComponent();

            }

     

            privatevoidbutton1_Click(objectsender, EventArgse)

            {

               

            }

     

                privatevoidSaveMailAttachments(Microsoft.Office.Interop.Outlook.MailItemmailItem)

                {

                    Microsoft.Office.Interop.Outlook.Attachmentsattachments = mailItem.Attachments;

                    if(attachments != null&& attachments.Count > 0)

                    {

                        for(inti = 1; i <= attachments.Count; i++)

                        {

                            Microsoft.Office.Interop.Outlook.Attachmentattachment = attachments[i];

                            if(attachment.Type == Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue)

                            {

                                stringfilename = Path.Combine(@"C:\Users\Excel\Desktop\Outlook_Attachments\", attachment.FileName);

                                attachment.SaveAsFile(filename);

                            }

                        }

                    }

                   

                }

     

         }

    }

     

    mercredi 21 mars 2012 22:21

Réponses

  • Hi ryguy,

    Welcome to the MSDN forum!

    You haven't initialize the mailItem object yet before passing it to the SaveMailAttachments() method.

    Please take a look at the following code:

            private void button1_Click(object sender, EventArgs e)
            {
                Outlook._Application oApp = new Outlook.Application();
                Outlook.NameSpace oNS = oApp.GetNamespace("mapi");
                oNS.Logon("LatestProfile");
    
                Outlook.MAPIFolder oInbox = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
                
                Outlook.Items oItems = oInbox.Items;
                int i =0;
                foreach(Outlook.MailItem oMail in oItems)
                {
                    if (i < 20)
                    {
                        i++;
                        SaveMailAttachments(oMail);
                    }
                    else
                    {
                        break;
                    }
                }
    
                MessageBox.Show("Done");
    
            }
    
            private void SaveMailAttachments(Outlook.MailItem mailItem)
            {
                    Outlook.Attachments attachments = mailItem.Attachments;
                    if (attachments != null && attachments.Count > 0)
                    {
                        for (int i = 1; i <= attachments.Count; i++)
                        {
                            Outlook.Attachment attachment = attachments[i];
                            if (attachment.Type == Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue)
                            {
                                string filename = Path.Combine(@"E:\Test\Attachment\", attachment.FileName);
                                attachment.SaveAsFile(filename);
                            }
                        }
                    }
            }

    For further questions about outlook development, please try the dedicated forum:

    http://social.msdn.microsoft.com/Forums/en/outlookdev/threads 

    Office Developer Center > Microsoft Office for Developers Forums Outlook for Developers

    Have a nice day.

    yoyo


    Yoyo Jiang[MSFT]
    MSDN Community Support | Feedback to us


    vendredi 23 mars 2012 07:09
  • Well, sorry for not make it clearly to you, ryguy.

    I add the following code at the beginning of the class(just in the pile of "Using..."):

       using System.Windows.Forms;
       using Outlook=Microsoft.Office.Interop.Outlook;
       using System.IO;

    In this way, we create an alias for the namespace "Microsoft.Office.Interop.Outlook" as "Outlook". 

    Have a nice day.


    Yoyo Jiang[MSFT]
    MSDN Community Support | Feedback to us

    lundi 26 mars 2012 04:30
  • DamianD, over at the Outlook Discussion Forum figured it out.  Here's the link:

    http://social.msdn.microsoft.com/Forums/en-US/outlookdev/thread/f708957f-b82d-4bb1-9655-41c13550d24e


    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);
                            }
                        }
                    }
            }
                   
        }
    }

    Ryan Shuell

    mercredi 11 avril 2012 22:17
  • Thanks for your post.

    That sounds strange!

    According to the message, there seems to be a name conflict in the "WindowsFormsApplication20.exe" and "Outlook.dll". 

    Consider casting this object to type 'dynamic' when debugging or building with the 'Embed Interop Types' property set to false.

    Based on this sentence, please do the following steps:

    1. Expand the References node and go to "Microsoft.Office.Interop.Outlook". Right Click on it and goes to "Properties" item. In the Properties panel, set the "Embed Interop Type" to false. 

    2. Try the following code:

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


    If it doesn't work, I suggest you try the project from the beginning, or you can download my version and try it:https://skydrive.live.com/redir.aspx?cid=37142ebae462f7f1&resid=37142EBAE462F7F1!137&parid=37142EBAE462F7F1!118

    Note: This version is for Office 2010 with Microsoft Outlook 14.0 Object Library as a reference. You may need to change it according to the specific office version. [ Microsoft Outlook 12.0 Object Library --Office 2007; Microsoft Outlook 11.0 Object Library --Office 2003]

    Also, are there already some mails in the outlook inbox? Please forgive me if this sounds stupid. 

    Hope it helps. 

    Have a nice day.

    yoyo


    Yoyo Jiang[MSFT]
    MSDN Community Support | Feedback to us

    • Marqué comme réponse ryguy72 mercredi 11 avril 2012 22:22
    lundi 2 avril 2012 08:42
  • Hi Ryan,

    Do you have added the PIA assemblies appropriate? What's the office version on your computer? As I have mentioned in my last response, if you have Office 2010 installed, you should add the reference Microsoft Outlook 14.0 Object Library. If it is Office 2007 installed, Microsoft Outlook 12.0 Object Library should be added.  

    Meanwhile, I'm trying to involve some senior engineers into this issue, and it takes some time. You patience will be greatly appreciated.

    Thanks.


    Yoyo Jiang[MSFT]
    MSDN Community Support | Feedback to us


    jeudi 5 avril 2012 02:37
  • Hi Ryan,

    When you said that the codes jump from foreach(...) to MessageBox.Show(), were you debugging the codes line by line?   If so, could you please double check the object oInbox and oItmes.Count property? 


    Michael Sun [MSFT]
    MSDN Community Support | Feedback to us

    • Marqué comme réponse ryguy72 mercredi 11 avril 2012 22:22
    jeudi 5 avril 2012 05:24
  • Hi Ryan,

    I mean the oItems.Count property.  Thanks!


    Michael Sun [MSFT]
    MSDN Community Support | Feedback to us

    • Marqué comme réponse ryguy72 mercredi 11 avril 2012 22:22
    jeudi 5 avril 2012 15:37
  • Hi Ryan,

    Could you please check the oInbox object?  We can get the folder path by oInbox.FoderPath.  Generally, its value will be YourMailAccount@***.com/Inbox.  You can check whether the mail account is correct since maybe your Outlook has configured to have several accounts.   Also, please double check whether there are target mail objects in the Inbox folder.  Maybe all the mails are in other folders and not the Inbox folder. 

    Besides, you can also try the codes in another computer to see if it works fine. 

    Good day!

    Thanks


    Michael Sun [MSFT]
    MSDN Community Support | Feedback to us

    • Marqué comme réponse ryguy72 mercredi 11 avril 2012 22:22
    lundi 9 avril 2012 03:48
  • Hi Ryan,

    Thanks for the following up!   Please understand that we are not experts of Outlook programming, but we are doing the best to help you figure out the issue. 

    Besides, let double confirm that our app has connected the Outlook instance by the following codes.  We can use F11 to debug the codes line by line, if the app goes to this line of codes, application = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application; and returns the correct value, I think we have connected to the Outlook instance successfully.   Then we can check the inbox value and its FolderPath value.   (Sorry for my typo in the last post, it should be FolderPath proerty). 

                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;


    Michael Sun [MSFT]
    MSDN Community Support | Feedback to us

    • Marqué comme réponse ryguy72 mercredi 11 avril 2012 22:22
    mardi 10 avril 2012 02:47
  • Hi Ryan,

    Actually, I am curious of why it happens as well.  :)   I think the problem is not at C# side since the sample codes we provided is what we generally do to open Outlook default inbox folder.   The problem could be Outlook related settings, which is not my expertise.   Could you please create a new thread and summurize the problem at Outlook programming forum, http://social.msdn.microsoft.com/Forums/en-US/outlookdev/threads?   There are many experts there willing to help us.  

    If you find the root cause there, would you mind also sharing the knowledge here to benefit more community members?  

    Good day!

    Thanks


    Michael Sun [MSFT]
    MSDN Community Support | Feedback to us

    • Marqué comme réponse ryguy72 mercredi 11 avril 2012 22:21
    mercredi 11 avril 2012 03:06

Toutes les réponses

  • Hi ryguy72

    There is nothing inside button1 Click as per your code

    privatevoidbutton1_Click(objectsender, EventArgse)

            {

               

            }

    I think you need to call the method SaveMailAttachments() inside that...



    Harshad..... Always 4 U

    jeudi 22 mars 2012 06:26
  • Yes, it would seem to be quite easy, but that doesn't work.  Please see this screen shot:

    I get a red squiggle line under 'SaveMailAttachments(mailItem)'.

    Error is:  mailItem does not exist in the current context.  If I take that out, I get an error about 'No overload for method 'SaveMailAttachments' takes 0 arguments', of course.  An argument needs to be passed, but what is the argument?

    jeudi 22 mars 2012 14:14
  • As you say on first post, you making a example that download something from outlook, so you should pass this 'something' as param.
    jeudi 22 mars 2012 14:54
  • not sure exactly what you need give as param, because i do not ever use this MailItem.

    jeudi 22 mars 2012 14:55
  • Hi ryguy,

    Welcome to the MSDN forum!

    You haven't initialize the mailItem object yet before passing it to the SaveMailAttachments() method.

    Please take a look at the following code:

            private void button1_Click(object sender, EventArgs e)
            {
                Outlook._Application oApp = new Outlook.Application();
                Outlook.NameSpace oNS = oApp.GetNamespace("mapi");
                oNS.Logon("LatestProfile");
    
                Outlook.MAPIFolder oInbox = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
                
                Outlook.Items oItems = oInbox.Items;
                int i =0;
                foreach(Outlook.MailItem oMail in oItems)
                {
                    if (i < 20)
                    {
                        i++;
                        SaveMailAttachments(oMail);
                    }
                    else
                    {
                        break;
                    }
                }
    
                MessageBox.Show("Done");
    
            }
    
            private void SaveMailAttachments(Outlook.MailItem mailItem)
            {
                    Outlook.Attachments attachments = mailItem.Attachments;
                    if (attachments != null && attachments.Count > 0)
                    {
                        for (int i = 1; i <= attachments.Count; i++)
                        {
                            Outlook.Attachment attachment = attachments[i];
                            if (attachment.Type == Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue)
                            {
                                string filename = Path.Combine(@"E:\Test\Attachment\", attachment.FileName);
                                attachment.SaveAsFile(filename);
                            }
                        }
                    }
            }

    For further questions about outlook development, please try the dedicated forum:

    http://social.msdn.microsoft.com/Forums/en/outlookdev/threads 

    Office Developer Center > Microsoft Office for Developers Forums Outlook for Developers

    Have a nice day.

    yoyo


    Yoyo Jiang[MSFT]
    MSDN Community Support | Feedback to us


    vendredi 23 mars 2012 07:09
  • Thanks for stepping in, Yoyo.  This kind of makes sense, but not toally, because I am still getting an error.  Here is my modified code (based on what you gave me):

    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 Microsoft.Office.Interop.Outlook;
    using System.IO;

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

            private void button1_Click(object sender, EventArgs e)
            {
                Outlook._Application oApp = new Outlook.Application();
                Outlook.NameSpace oNS = oApp.GetNamespace("mapi");
                oNS.Logon("LatestProfile");

                Outlook.MAPIFolder oInbox = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);

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

                MessageBox.Show("Done");

            }

            private void SaveMailAttachments(Outlook.MailItem mailItem)
            {
                Outlook.Attachments attachments = mailItem.Attachments;
                if (attachments != null && attachments.Count > 0)
                {
                    for (int i = 1; i <= attachments.Count; i++)
                    {
                        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);
                        }
                    }
                }
            }

        }
    }

    I still get 1 error on this line:

    private void SaveMailAttachments(Outlook.MailItem mailItem)

    Error:

    The type or namespace name 'Outlook' could not be found (are you missing a using directive or an assembly reference?)

    I've seen this before, btu I don't really understand what the error is about.  I DO HAVE A REFERENCE TO OUTLOOK!!

    using Microsoft.Office.Interop.Outlook;

    Project > Add Reference > COM > Microsoft Outlook 14.0 Object Library

    So, why would I continue to get an error about Outlook NOT being referenced.  As far as I can tell, it IS referenced!!!

    vendredi 23 mars 2012 14:01
  • Well, sorry for not make it clearly to you, ryguy.

    I add the following code at the beginning of the class(just in the pile of "Using..."):

       using System.Windows.Forms;
       using Outlook=Microsoft.Office.Interop.Outlook;
       using System.IO;

    In this way, we create an alias for the namespace "Microsoft.Office.Interop.Outlook" as "Outlook". 

    Have a nice day.


    Yoyo Jiang[MSFT]
    MSDN Community Support | Feedback to us

    lundi 26 mars 2012 04:30
  • thanks again, Yoyo.  There still seems to be a problem here.  The focus skips from here:

    foreach (Outlook.MailItem oMail in oItems)

     

    to here:

    MessageBox.Show("Done");

     

    The code never enters the For Each . . . Loop

     

    In the immeidate window, I get this:

    ?oItems
    {System.__ComObject}
        [System.__ComObject]: {System.__ComObject}
    ?Outlook.MailItem
    Embedded interop type 'Microsoft.Office.Interop.Outlook.MailItem' is defined in both 'WindowsFormsApplication18.exe' and 'Outlook.dll'. Some operations on objects of this type are not supported while debugging. Consider casting this object to type 'dynamic' when debugging or building with the 'Embed Interop Types' property set to false.
    ?oMail
    The name 'oMail' does not exist in the current context

     

    What am I missing here?

     

    I did some research on the web, and saw an article that said that I need to add another using reference.  I added this:

    using System.Net.Mail;

     

    That didn't help at all.  What's wrong now???

     

    vendredi 30 mars 2012 21:21
  • Hello.

    try adding these 2 reference

    using System.Net.Mail;
    using System.Net;

    samedi 31 mars 2012 07:43
  • Hummm, same as before!  Everything in the For Each . . . Loop gets skipped.  I get the following values for the following variables:

    ?Outlook.MailItem
    Embedded interop type 'Microsoft.Office.Interop.Outlook.MailItem' is defined in both 'WindowsFormsApplication20.exe' and 'Outlook.dll'. Some operations on objects of this type are not supported while debugging. Consider casting this object to type 'dynamic' when debugging or building with the 'Embed Interop Types' property set to false.
    ?oMail
    The name 'oMail' does not exist in the current context
    ?oItems
    {System.__ComObject}
        [System.__ComObject]: {System.__ComObject}

    This is so hard to debug!  I get no errors, but everything inside the loop gets skipped over.  I think it does have something to do with one of the using statements.  I don't knwo what though.  HARD TO DEBUG!!


    Ryan Shuell

    samedi 31 mars 2012 16:08
  • Thanks for your post.

    That sounds strange!

    According to the message, there seems to be a name conflict in the "WindowsFormsApplication20.exe" and "Outlook.dll". 

    Consider casting this object to type 'dynamic' when debugging or building with the 'Embed Interop Types' property set to false.

    Based on this sentence, please do the following steps:

    1. Expand the References node and go to "Microsoft.Office.Interop.Outlook". Right Click on it and goes to "Properties" item. In the Properties panel, set the "Embed Interop Type" to false. 

    2. Try the following code:

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


    If it doesn't work, I suggest you try the project from the beginning, or you can download my version and try it:https://skydrive.live.com/redir.aspx?cid=37142ebae462f7f1&resid=37142EBAE462F7F1!137&parid=37142EBAE462F7F1!118

    Note: This version is for Office 2010 with Microsoft Outlook 14.0 Object Library as a reference. You may need to change it according to the specific office version. [ Microsoft Outlook 12.0 Object Library --Office 2007; Microsoft Outlook 11.0 Object Library --Office 2003]

    Also, are there already some mails in the outlook inbox? Please forgive me if this sounds stupid. 

    Hope it helps. 

    Have a nice day.

    yoyo


    Yoyo Jiang[MSFT]
    MSDN Community Support | Feedback to us

    • Marqué comme réponse ryguy72 mercredi 11 avril 2012 22:22
    lundi 2 avril 2012 08:42
  • Thanks for the follow through, Yoyo!  I appreciate it!!  I'm sad to say, this still is NOT working.  I get an error under this line:

    dynamic oItems = Outlook.MailItem.mailItem;

    'Microsoft.Office.Interop.Outlook.MailItem' does not contain a definition for 'mailItem'

    I get that is I copy your sample code from above.  I also downloaded the file that you posted, and I tried to run that project.

    Basically, I opened the project, and set a break point on this line (right after the button_click event):

    Outlook._Application oApp = new Outlook.Application();

    I hit F11 a few times.  After I get to this line:

    foreach(var oMail in oItems)

    The code skips down here:

    MessageBox.Show("Done");

    It doesn't evaluate anything in the Inbox!!  It's almost like ti can't make the connection to the Outlook Inbox!!  I have Outlook open and I have many emails in my Inbox; I have may attachments on many of those emails.  How can I force C# to connect to my Inbox.  I think that is the problem.

    Finally, I have the following values/variables combination:

    ?Outlook.Items
    Embedded interop type 'Microsoft.Office.Interop.Outlook.Items' is defined in both 'TestSaveEmailAttachments.exe' and 'Outlook.dll'. Some operations on objects of this type are not supported while debugging. Consider casting this object to type 'dynamic' when debugging or building with the 'Embed Interop Types' property set to false.
    ?oItems
    {System.__ComObject}
        [System.__ComObject]: {System.__ComObject}
    ?oInbox.Items
    {System.__ComObject}
        [System.__ComObject]: {System.__ComObject}

    I'm very curious as to what is happening now.  I'm looking forward to your response.

    Thanks so much for all the help with this!!!


    Ryan Shuell

    mercredi 4 avril 2012 12:38
  • Hi Ryan,

    Do you have added the PIA assemblies appropriate? What's the office version on your computer? As I have mentioned in my last response, if you have Office 2010 installed, you should add the reference Microsoft Outlook 14.0 Object Library. If it is Office 2007 installed, Microsoft Outlook 12.0 Object Library should be added.  

    Meanwhile, I'm trying to involve some senior engineers into this issue, and it takes some time. You patience will be greatly appreciated.

    Thanks.


    Yoyo Jiang[MSFT]
    MSDN Community Support | Feedback to us


    jeudi 5 avril 2012 02:37
  • I am using VS 2010 and Office 2010.  I downloaded and ran the project that you put up for me:

    https://skydrive.live.com/redir.aspx?cid=37142ebae462f7f1&resid=37142EBAE462F7F1!137&parid=37142EBAE462F7F1!118

    Outlook 2010 is open and running when I run the VS project.  Finally, I clicked on my Inbox (to make sure it has focus and emails load) before running the project.

    Here is a snapshot of all my references.  I just tried this again.  My results are just like I described before.  The logic skips from here:

    foreach(var oMail in oItems)

    To here:

    MessageBox.Show("Done");

    It seems like the code enters the For Each loop and then jumps to the 'Done' message.  It's like VS doesn't even recognize Outlook.

    Here is an image of my References:

    Thanks for all your help with this thing!!  I really appreciate it!!


    Ryan Shuell


    • Modifié ryguy72 jeudi 5 avril 2012 03:50
    jeudi 5 avril 2012 03:12
  • Hi Ryan,

    When you said that the codes jump from foreach(...) to MessageBox.Show(), were you debugging the codes line by line?   If so, could you please double check the object oInbox and oItmes.Count property? 


    Michael Sun [MSFT]
    MSDN Community Support | Feedback to us

    • Marqué comme réponse ryguy72 mercredi 11 avril 2012 22:22
    jeudi 5 avril 2012 05:24
  • Interesting; I don't think I have an oInbox.Count property. Mine looks slightly different from yours.

    Ryan Shuell

    jeudi 5 avril 2012 15:35
  • Hi Ryan,

    I mean the oItems.Count property.  Thanks!


    Michael Sun [MSFT]
    MSDN Community Support | Feedback to us

    • Marqué comme réponse ryguy72 mercredi 11 avril 2012 22:22
    jeudi 5 avril 2012 15:37
  • It seems like VS is not connecting to Outlook.  It seesm to think that there are NO ATTACHMENTS, but there are some.  When I do this using a VBA script, it works just fine. 


    Ryan Shuell

    jeudi 5 avril 2012 15:42
  • Hi Ryan,

    Could you please check the oInbox object?  We can get the folder path by oInbox.FoderPath.  Generally, its value will be YourMailAccount@***.com/Inbox.  You can check whether the mail account is correct since maybe your Outlook has configured to have several accounts.   Also, please double check whether there are target mail objects in the Inbox folder.  Maybe all the mails are in other folders and not the Inbox folder. 

    Besides, you can also try the codes in another computer to see if it works fine. 

    Good day!

    Thanks


    Michael Sun [MSFT]
    MSDN Community Support | Feedback to us

    • Marqué comme réponse ryguy72 mercredi 11 avril 2012 22:22
    lundi 9 avril 2012 03:48

  • This is what I get for 'oInbox.FoderPath'

    ?oInbox.FoderPath

    Member 'FoderPath' on embedded interop type 'Microsoft.Office.Interop.Outlook.MAPIFolder' cannot be evaluated while debugging since it is never referenced in the program. Consider casting the source object to type 'dynamic' first or building with the 'Embed Interop Types' property set to false when debugging

    I do have 2 email accounts configured.  I didn't think that made a difference.  I open Outlook, select 1 email account, and then open my VS project and hit F11 until I get to the image you see above.

    In Outlook 2010, I click File > Account Information and I see that one email account is 'MAPI' and one is 'IMAP/SMTP'.  I'm not sure what difference this makes.  I'd expect the code would still connect to at least 1 of these accounts and start downloading attachments for that one.  In reality, the code seems to ignore BOTH accounts and since it thinks there are 0 items in my Inbox; it skips through the loop and goes right to the end.

    My oInbox.Items DynamicView looks TOTALLY different from yours, which you posted on April 5th!!


    Ryan Shuell

    lundi 9 avril 2012 18:04
  • Hi Ryan,

    Thanks for the following up!   Please understand that we are not experts of Outlook programming, but we are doing the best to help you figure out the issue. 

    Besides, let double confirm that our app has connected the Outlook instance by the following codes.  We can use F11 to debug the codes line by line, if the app goes to this line of codes, application = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application; and returns the correct value, I think we have connected to the Outlook instance successfully.   Then we can check the inbox value and its FolderPath value.   (Sorry for my typo in the last post, it should be FolderPath proerty). 

                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;


    Michael Sun [MSFT]
    MSDN Community Support | Feedback to us

    • Marqué comme réponse ryguy72 mercredi 11 avril 2012 22:22
    mardi 10 avril 2012 02:47
  • Thanks for the follow through, Michael.  I didn't expect it to get this involved; didn't expect to put so much time or effort into this.  I don't need this for work, or anything like that, but rather, I am curious to see how it all works.  I'm teaching myself C# now (trying to teach myself). 

    As an aside, I've done something similar, using VBA.  Excel & Access can easily download all Outlook email attachments.  It seems like it is significantly harder to do this in C#.

    Anyway, based on your above-posted script, this is what I have now.

    ?account
    "\\\\Outlook Data File\\Inbox"

    Here are a couple new screen shots:

    After this line:

    foreach(var oMail in oItems)

    The focus (the yellow highlight line), skips here:

    MessageBox.Show("Done");

    In the Immediate Window:

    ?oMail
    The name 'oMail' does not exist in the current context


    Ryan Shuell


    • Modifié ryguy72 mardi 10 avril 2012 23:50
    mardi 10 avril 2012 23:45
  • Hi Ryan,

    Actually, I am curious of why it happens as well.  :)   I think the problem is not at C# side since the sample codes we provided is what we generally do to open Outlook default inbox folder.   The problem could be Outlook related settings, which is not my expertise.   Could you please create a new thread and summurize the problem at Outlook programming forum, http://social.msdn.microsoft.com/Forums/en-US/outlookdev/threads?   There are many experts there willing to help us.  

    If you find the root cause there, would you mind also sharing the knowledge here to benefit more community members?  

    Good day!

    Thanks


    Michael Sun [MSFT]
    MSDN Community Support | Feedback to us

    • Marqué comme réponse ryguy72 mercredi 11 avril 2012 22:21
    mercredi 11 avril 2012 03:06
  • DamianD, over at the Outlook Discussion Forum figured it out.  Here's the link:

    http://social.msdn.microsoft.com/Forums/en-US/outlookdev/thread/f708957f-b82d-4bb1-9655-41c13550d24e


    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);
                            }
                        }
                    }
            }
                   
        }
    }

    Ryan Shuell

    mercredi 11 avril 2012 22:17
  • Hi Ryan,

    Thank you for sharing the solution here! 

    Good day!


    Michael Sun [MSFT]
    MSDN Community Support | Feedback to us

    jeudi 12 avril 2012 01:34