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

Rog*_*son 4 c# microsoft-graph-mail microsoft-graph-api

我正在尝试使用 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();
Run Code Online (Sandbox Code Playgroud)

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

为什么是这样?

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

这是一个权限的事情,我可以通过某种方式增加我们AD应用程序注册的权限来获得这个权限吗?

还是还有其他事情发生?

Mar*_*eur 7

Graph Client 只是 REST API 的包装器,它不执行对象的延迟加载。

User对象来自 AAD,同时MailFolders来自 Exchange,并且每个对象都有自己的端点。

正如您所指出的,您的Users请求工作正常。为了检索用户的,您需要从 中MailFolders获取Id或并使用它对 发出单独的请求。您还需要发出另一个请求才能获取消息:UserPrincipalNameUserMailFolders

// 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();
Run Code Online (Sandbox Code Playgroud)

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

鉴于您只使用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();
Run Code Online (Sandbox Code Playgroud)