c# – 使用Visual Studio枚举Outlook邮箱

我有以下类,旨在返回文件夹中所有电子邮件主题

它是针对运行在Windows 7 64位上的Outlook 2007的Visual Studio 2008

using System;
using System.Windows;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Outlook;

namespace MarketingEmails
{
public class MailUtils
{

  public static string[] processMailMessages(object outlookFolder)
    // Given an Outlook folder as an object reference,return
    // a list of all the email subjects in that folder
    {

        // Set a local object from the folder passed in
        Folder theMailFolder = (Folder)outlookFolder;

        string[] listSubjects = new string[theMailFolder.Items.Count];
        int itemCount = 0;

        // Now process the MAIL items
        foreach (MailItem oItem in theMailFolder.Items)
        {
            listSubjects[itemCount] = oItem.Subject.ToString();
            itemCount++;
        }
        return listSubjects;
    }

}

}

但是代码抛出以下异常:

无法将“System .__ ComObject”类型的COM对象强制转换为接口类型“Microsoft.Office.Interop.Outlook.MailItem”.此操作失败,因为由于以下错误,IID为“{00063034-0000-0000-C000-000000000046}”的接口的COM组件上的QueryInterface调用失败:不支持此类接口(HRESULT异常:0x80004002(E_NOINTERFACE)) .

我理解发生的错误是因为它试图处理所选邮箱中的ReportItem.

我不明白的是,当我指定时,为什么尝试ro处理非邮件项目:

foreach (MailItem oItem in theMailFolder.Items)

如果我希望它处理邮箱中的报告项条目,我会写:

foreach (ReportItem oItem in theMailFolder.Items)

我非常想知道这是一个错误还是只是我的误解

问候,
Nigel Ainscoe

解决方法

原因是集合Items包含MailItem和ReportItem实例.在左侧指定MailItem不会过滤列表,它只是说明您希望列表中的类型.

你需要做的是过滤你想要的类型

foreach ( MailItem oItem in theMailFolder.Items.OfType<MailItem>()) {
  ..
}

OfType方法仅返回集合中与该特定类型匹配的值.

相关文章

原文地址:http://msdn.microsoft.com/en-us/magazine/cc163...
前言 随着近些年微服务的流行,有越来越多的开发者和团队所采...
最近因为比较忙,好久没有写博客了,这篇主要给大家分享一下...
在多核CPU在今天和不久的将来,计算机将拥有更多的内核,Mic...
c语言输入成绩怎么判断等级
字符型数据在内存中的存储形式是什么