Retrieve Current Email Body In Outlook

我们两清 提交于 2019-12-07 00:19:45

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/10935611/retrieve-current-email-body-in-outlook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!