如何使用ExchangeService访问共享邮箱(Outlook 2013)

时间:2015-10-06 15:21:24

标签: c# outlook exchange-server

我正在尝试使用ExchangeService访问Outlook中的第二个邮箱。但是当我运行应用程序时,它会抓取我的主电子邮件。值得注意的是,我在这里使用Windows身份验证,并且我需要这样才能工作。

var useExchangeServer = new UseExchangeServer("SECONDEMAIL@mycompany.com");
var messages = useExchangeServer.LoadMessages(1);

foreach (var message in messages){ //At this point message has the wrong email...
...
}

这是我的" UseExchangeServer"类

public UseExchangeServer(string mailBox)
    {
        _service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
        _service.UseDefaultCredentials = true;
        _service.AutodiscoverUrl(mailBox);
    }

public FindItemsResults<Item> GetLastItems(int numberOfItems)
    {
        return _service.FindItems(WellKnownFolderName.Inbox, new ItemView(numberOfItems));
    }

public IEnumerable<EmailMessage> LoadMessages(int numberOfMessages)
    {
        var findResults = GetLastItems(numberOfMessages);

        foreach (var item in findResults.Items)
        {
            var message = EmailMessage.Bind(_service, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments));
            message.Load();
            yield return message;
        }
    }

1 个答案:

答案 0 :(得分:2)

您需要使用FolderId重载来指定要访问的邮箱,否则将使用属于您正在使用的凭据的邮箱,因此您需要使用以下代码执行以下操作

public UseExchangeServer(string mailBox)
{
    _service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
    _service.UseDefaultCredentials = true;
    _service.AutodiscoverUrl(mailBox);
}

 public FindItemsResults<Item> GetLastItems(int numberOfItems,string mailBox)
{
    FolderId FolderToAccess = new FolderId(WellKnownFolderName.Inbox,mailBox);
    return _service.FindItems(FolderToAccess, new ItemView(numberOfItems));
}

public IEnumerable<EmailMessage> LoadMessages(int numberOfMessages)
{
    var findResults = GetLastItems(numberOfMessages);

    foreach (var item in findResults.Items)
    {
        var message = EmailMessage.Bind(_service, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments));
        message.Load();
        yield return message;
    }
}

干杯 格伦