繁体   English   中英

使用 MS Graph 读取用户电子邮件 API C#

[英]Reading user emails using MS Graph API C#

我正在尝试使用 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 Client只是REST API的包装器,它不会延迟加载对象。

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

如您所述,您的Users请求正常运行。 为了获取用户的MailFolders你需要采取的Id或者UserPrincipalNameUser并用它来作为一个sperate请求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();

如果您只关心“众所周知的”邮件文件夹,则可以使用众所周知的名称来简化此请求。 例如,您可以像这样请求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();

想知道您是否可以专门针对建立 Graph 客户端提供额外的代码:

var 客户端 = 等待 GetClient(); //获取一个带有客户端ID,秘密的客户端

我也尝试使用客户端 ID 和机密,但无法使其正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM