【问题标题】:Reading user emails using MS Graph API C#使用 MS Graph API C# 读取用户电子邮件
【发布时间】:2019-03-23 07:52:28
【问题描述】:

我正在尝试使用 MS Graph API 从特定邮箱读取电子邮件。

var client = await GetClient(); //getting a client with client id, secret
var users = await client.Users.Request()
                 .Filter("startswith(displayName,'roger')")
                 .GetAsync(); //getting the users matching a criteria

var user = users.First(); //get the first user

//log the user name, this works fine
log.LogInformation("Found user " +  user.DisplayName);

//this is null
var messages = user.MailFolders?.FirstOrDefault();

我从这里获取的用户那里获得了所有正确的数据,但用户 mailFolders 属性是 null

这是为什么?

我们想要扫描特定邮箱中的电子邮件并处理这些电子邮件和附件。我认为这可能是做到这一点的正确方法。 但我坚持以上,MS Graph 上的文档,尤其是 .NET API 的文档是如此。

是不是权限的事情,我能不能通过某种方式增加我们AD应用注册的权限来获得这个权限?

或者这里还有其他事情吗?

【问题讨论】:

  • 您能否在Graph Explorer 查询相关用户帐户是否有交换电子邮件帐户?我通常使用 fiddler 或类似工具来跟踪对 Graph 的调用,然后使用 Graph Explorer 进行故障排除

标签: c# microsoft-graph-api microsoft-graph-mail


【解决方案1】:

图形客户端只是 REST API 的包装器,它不会延迟加载对象。

User 对象来自 AAD,而 MailFolders 来自 Exchange,每个对象都有自己的端点。

如您所述,您的 Users 请求工作正常。为了检索用户的MailFolders,您需要从User 中获取IdUserPrincipalName,并使用它对MailFolders 进行单独请求。您还需要发出另一个请求以获取消息:

// Get all users with a displayName of roger*
var users = await graphClient
    .Users
    .Request()
    .Filter("startswith(displayName,'roger')")
    .GetAsync();

// Get the first user's mail folders
var mailFolders = await graphClient
    .Users[users[0].Id] // first user's id
    .MailFolders
    .Request()
    .GetAsync();

// Get messages from the first mail folder
var messages = await graphClient
    .Users[users[0].Id] // first user'd id
    .MailFolders[mailFolders[0].Id] // first mail folder's id
    .Messages
    .Request()
    .GetAsync();

如果您只关心“知名”邮件文件夹,您可以使用well-known name 简化此请求。例如,您可以像这样请求inbox

// Get message from the user's inbox
var inboxMessages = await graphClient
    .Users[users[0].Id] // first user'd id
    .MailFolders["inbox"]
    .Messages
    .Request()
    .GetAsync();

鉴于您只使用 id 值,您可以通过仅请求 id 属性来优化它:

// Get all users with a displayName of roger*
var users = await graphClient
    .Users
    .Request()
    .Select("id") // only get the id
    .Filter("startswith(displayName,'roger')")
    .GetAsync();

// Get the first user's mail folders
var mailFolders = await graphClient
    .Users[users[0].Id] // first user's id
    .MailFolders
    .Request()
    .Select("id") // only get the id
    .GetAsync();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多