none
extract the body & the attachments from new mails received in Outlook RRS feed

  • Question

  • I'm currently trying to extract the body and the attachments from the new mails I receive in Outlook.

    The code looks like this 

      private Outlook.ApplicationEvents_11_NewMailExEventHandler handler;
            private void ThisAddIn_Startup(object sender, System.EventArgs e)
            {
                this.Application.NewMailEx += handler;
            }
    
    
     private void Application_NewMailEx(string EntryIDCollection)
            {
              
                string[] entryIdArray = EntryIDCollection.Split(',');
                foreach (string entryId in entryIdArray)
                {
                    
                   
                    try
                    {
                        Outlook.MailItem item = (Outlook.MailItem)Application.Session.GetItemFromID(EntryIDCollection, null);
                        //Outlook.Folder Inbox = (Outlook.Folder)Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
                        //foreach(item in Inbox)
                      
                        string fullpath = string.Format(@"D:\tmp\{0}.txt", item.Subject);
                  
                                          
                        
                    }
                    catch (System.Exception e)
                    {
                        MessageBox.Show(e.Message);
                    }
                }
            }

    The ideea is that for each new item in Inbox, to extract the sender,subject,the mail body and attachments. The code above works but it only shows me the sender of the mail,the receiver, the date and the subject. Any hint/code snippet how to approach the problem will be great.


    Thanks in advance

    • Edited by intenesi Monday, March 31, 2014 1:52 PM
    Monday, March 31, 2014 1:50 PM

Answers

  • The problem is the IMAP protocol(dont know why) . When I change my email to POP3 protocol, the message body is retrieved and the attachments download. Thanks for your help

    Tested also on outlook 2013(IMAP Protocol) . Working

    • Edited by intenesi Thursday, April 3, 2014 11:40 AM
    • Marked as answer by intenesi Thursday, April 3, 2014 11:59 AM
    Thursday, April 3, 2014 9:06 AM

All replies

  • Hello,

    Please check out the Attachments property which allows you access all attachments. Use the Body or HTMLBody properties for accessing the body.

    The Chapter 17: Working with Item Bodies chapter available in MSDN describes all possible ways accessing the body.
    Monday, March 31, 2014 2:00 PM
  • I have a problem. I tried different methods to try to get the attachments(at least the number of attachments from every mail received) and all failed. I have a snippet like this : 

     string subj = item.Subject;
     string to = item.To;
     string bec = item.BCC;
    
    string final = "Sender: " + item.SenderEmailAddress + "\r\n" + "Subject: " + subj + "\r\n" + "BCC: " + bec + "\r\n" + "TO: " + to + "\r\n\n";
                       System.IO.File.AppendAllText(@"D:\tmp\atr.txt", final);

    Here, i get the sender/subject/bcc of every new mail. 

    Now i've tried to get the attachments 

     int nrAttachments = item.Attachments.Count;
     for(int i=1;i<=nrAttachments;++i)
                        {
                            item.Attachments[i].SaveAsFile(@"D:\tmp\");
                        }

    And it does not saves me any attachment.

    int nrAttachments = item.Attachments.Count;								
    

    Well, even this part does not work.It always gives me 0 as number of attachments.

    The big problem is that after i tried to get the attachments(loaded my plugin), my outlook licence got disabled and a message box appears with the message "The copy of microsoft office is not activated. You have 4 days to activate  and so on". Does anybody knows why?  And if somebody has an ideea how to get the attachments , let me know

    Tuesday, April 1, 2014 10:24 AM
  • Hello intensi,

    At least you need to specify the file name, not only the path (a folder).

    Please read more about this in the How to: Programmatically Save Attachments from Outlook E-Mail Items article. There also you can find a sample code in C#.

    Tuesday, April 1, 2014 11:36 AM
  • If the count equals to zero, the mail item doesn't have any items/files attached.

    Also I'd recommedn releasing underlying COM objects instantly. I have noticed the following code:

    int nrAttachments = item.Attachments.Count;

    Each time you call the Attachments property the reference counter is increased. So, the object returned by the property should be released.

    See Systematically Releasing Objects for more information. Use System.Runtime.InteropServices.Marshal.ReleaseComObject to release an Outlook object when you have finished using it. Then set a variable to Nothing in Visual Basic (null in C#) to release the reference to the object.

    Tuesday, April 1, 2014 11:58 AM
  • I've also tried giving name to the files, still it did not work. I saw that article but the as you can see , I'm using NewMailEx event , not NewMail, which gives me an EntryID for every new mail I receive.
    Tuesday, April 1, 2014 11:58 AM
  • Actually, it doesn't matter what event handler you are using at the moment. Saving mail items is identical for all cases.

    >  it did not work

    Could you please be more specific? Did you try to debug? Do you get any exceptions or error messages?

    Tuesday, April 1, 2014 12:04 PM
  • No exception, no error message. I've sent myself a message with a subject/a body and 2 attachments. This is what is shows while debugging




    • Edited by intenesi Tuesday, April 1, 2014 2:05 PM
    Tuesday, April 1, 2014 1:58 PM
  • I noticed in your "get attachments" code that you're pre-incrementing the loop counter (++I). That wouldn't at best return attachments[1]. Does it work any better if your loop post-increments the loop counter?


    Ken Slovak MVP - Outlook

    Tuesday, April 1, 2014 2:05 PM
    Moderator
  • Did you try to debug the for loop instead?

    The article I mentioned above provides the following code:

    if (newEmail.Attachments.Count > 0)
    {
       for (int i = 1; i <= newEmail.Attachments.Count; i++)
       {
           newEmail.Attachments[i].SaveAsFile(@"C:\TestFileSave\" +newEmail.Attachments[i].FileName);
       }
    }
    

    Did you try to use it?

    Tuesday, April 1, 2014 2:14 PM
  • That part is commented. The code that I use now is this:

          private void Application_NewMailEx(string EntryIDCollection)
            {
              
                string[] entryIdArray = EntryIDCollection.Split(',');
                foreach (string entryId in entryIdArray)
                {
                    
                   
                    try
                    {
                      
                        Outlook.MailItem item = (Outlook.MailItem)Application.Session.GetItemFromID(EntryIDCollection, null);
                      
    
    
                        string subj = item.Subject;
                        string to = item.To;
                        string bec = item.BCC;
                        string body = item.Body;
                       
                        int count = item.Attachments.Count;
                       
                       
                    
                       string final = "Sender: " + item.SenderEmailAddress + "\r\n" + "Subject: " + subj + "\r\n" + "BCC: " + bec + "\r\n" + "TO: " + to + "\r\n\n";
                    
                       System.IO.File.AppendAllText(@"D:\tmp\atr.txt", final);
                       
                     
                        
    
                       Marshal.ReleaseComObject(item);
                        
                    }
                    catch (System.Exception e)
                    {
                        MessageBox.Show(e.Message);
                    }
                }
            }

    Tuesday, April 1, 2014 2:22 PM
  • That wouldn't do anything with the attachments, have you given up on them?


    Ken Slovak MVP - Outlook

    Tuesday, April 1, 2014 2:25 PM
    Moderator
  • I don't see anything strange in the code. Do you get anything strange at runtime?

    Tuesday, April 1, 2014 2:26 PM
  • I dont receive anything strange, no errors, no warning.

    I've tried 

      if (item.Attachments.Count > 0)
                        {
                            for (int i = 1; i <= item.Attachments.Count; i++)
                            {
                                item.Attachments[i].SaveAsFile(@"D:\tmp\" + item.Attachments[i].FileName);
                            }
                        }
                      
    still nothing . If I send myself a message with 2 attachments, the if statement will return false. 
    Tuesday, April 1, 2014 8:08 PM
  • It is impossible...

    Anyway, what Outlook version do you have installed on the problematic PC? I will test this scenario on my PC.

    Tuesday, April 1, 2014 8:20 PM
  • Please make sure that you check the item where you attached files, not any other email.
    Tuesday, April 1, 2014 9:03 PM
  • I dont understand. What do you mean?

    It could be a problem the fact that my outlook account type is IMAP/SMTP?


    I've tried also this solution seen in another topic
       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(@"d:\", attachment.FileName);
                            attachment.SaveAsFile(filename);
                        }
                    }
                }
            }

    still nothing
    • Edited by intenesi Wednesday, April 2, 2014 9:56 AM
    Tuesday, April 1, 2014 9:05 PM
  • That just doesn't make any sense. See what happens if you try this code in the Outlook VBA project. Use Alt+F11 to open the project and then in the ThisOutlookSession class module enter this code:

    Sub TestAttachments

    Dim mail As Outlook.MailItem

    Dim atts As Outlook.Attachments

    Set mail = Application.ActiveInspector.CurrentItem

    Set atts = mail.Attachments

    MsgBox "There are " & atts.Count & " attachments"

    End Sub

    Open a mail item with attachments and put your cursor in the Sub and press F5 to run the macro. Does it respond with the correct number of attachments?


    Ken Slovak MVP - Outlook

    Wednesday, April 2, 2014 1:33 PM
    Moderator
  • Did you configure Outlook for downloading headers only? Is this the case?

    Read more about this on the IMAP and always download full items page.

    Wednesday, April 2, 2014 1:38 PM
  • I've configured the Outlook after that tutorial Eugene and still no result.

    Ken, I dont understand the steps you said. I dont know anything about VB. Can you please detail it?

    I've pressed alt+ f11 and it makes a code analysis.From there I'm lost.

    And by the way, can anybody test it on his Outlook? maybe it's a problem of outlook version or the type of account I am using(IMAP). I'd really appreciate. For developing I've used Visual studio 2010




    • Edited by intenesi Thursday, April 3, 2014 8:43 AM
    Wednesday, April 2, 2014 7:05 PM
  • Use Alt+F11 to open the Outlook VBA project.

    Make sure the Project Explorer window is open. If it is not open use View, Project Explorer to open it.

    Expand the Microsoft Outlook Objects folder in the Project Explorer. Select ThisOutlookSession and double-click it to open the code window.

    Copy the following code and paste or enter it into the code window.

    Sub TestAttachments

    Dim mail As Outlook.MailItem

    Dim atts As Outlook.Attachments

    Set mail = Application.ActiveInspector.CurrentItem

    Set atts = mail.Attachments

    MsgBox "There are " & atts.Count & " attachments"

    End Sub

    Open a mail item that has attachments.

    Use Alt+F11 to get back to the VBA project, and put your cursor in the TestAttachments Sub.

    Press F5 to run the code.

    Does it display a MessageBox with the correct number of attachments?


    Ken Slovak MVP - Outlook

    Wednesday, April 2, 2014 8:30 PM
    Moderator
  • Maybe it's because is late and my head is not working anymore or idk but when I press alt + f11 just code analysis starts and nothing more. I also dont have Project Explorer in View tab. Proof 

    But I think I can aswer your question regarding the number of attachments , using OutlookSpy. When I send a message with , lets say, 2 attachments and a message body, when I click the message in Outlook and then Item in OutlookSpy, I can see that the message has 2 attachments and the text from the body is there.

    Wednesday, April 2, 2014 9:17 PM
  • The problem is the IMAP protocol(dont know why) . When I change my email to POP3 protocol, the message body is retrieved and the attachments download. Thanks for your help

    Tested also on outlook 2013(IMAP Protocol) . Working

    • Edited by intenesi Thursday, April 3, 2014 11:40 AM
    • Marked as answer by intenesi Thursday, April 3, 2014 11:59 AM
    Thursday, April 3, 2014 9:06 AM