Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve Current Email Body In Outlook

in my outlook addin I want to add a button on the Ribbon so when user click this button I want to retrieve the current selected email's body , I have this code but it retrieve only the first email from the inbox because the index is 1 :

Microsoft.Office.Interop.Outlook.Application myApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.NameSpace mapiNameSpace = myApp.GetNamespace("MAPI");
Microsoft.Office.Interop.Outlook.MAPIFolder myInbox = mapiNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
String body = ((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[1]).Body;

so how to retrieve the current opened email in outlook? , this method work for me but I need to get the index for the current email.

Thanks.

like image 906
Radi Avatar asked Jun 07 '12 16:06

Radi


2 Answers

You shouldn’t initialize a new Outlook.Application() instance each time. Most add-in frameworks provide you with an Outlook.Application instance, corresponding to the current Outlook session, typically through a field or property named Application. You are expected to use this for the lifetime of your add-in.

To get the currently-selected item, use:

Outlook.Explorer explorer = this.Application.ActiveExplorer();
Outlook.Selection selection = explorer.Selection;

if (selection.Count > 0)   // Check that selection is not empty.
{
    object selectedItem = selection[1];   // Index is one-based.
    Outlook.MailItem mailItem = selectedItem as Outlook.MailItem;

    if (mailItem != null)    // Check that selected item is a message.
    {
        // Process mail item here.
    }
}

Note that the above will let you process the first selected item. If you have multiple items selected, you might want to process them in a loop.

like image 129
Douglas Avatar answered Sep 17 '22 19:09

Douglas


On Top add reference to

using Outlook = Microsoft.Office.Interop.Outlook;

Then inside a method;

Outlook._Application oApp = new Outlook.Application();
if (oApp.ActiveExplorer().Selection.Count > 0)
            {
                Object selObject = oApp.ActiveExplorer().Selection[1];

                if (selObject is Outlook.MailItem)
                {
                    Outlook.MailItem mailItem = (selObject as Outlook.MailItem);
                    String htmlBody = mailItem.HTMLBody;
                    String Body = mailItem.Body;
                 }
             }

Also you can change the body which will show in outlook before viewing the mail.

like image 43
9T9 Avatar answered Sep 20 '22 19:09

9T9