Mailkit 以编程方式连接到 Office365

问题描述

我需要以编程方式 (C#) 从我的 Office365 帐户接收电子邮件。 我决定使用 Mailkit 并在 Azure 门户上创建应用程序密码。 我注册一个新应用,设置了它的重定向 Uri 并给了它一些权限:

Permissions

然后我创建了一个客户端密码,无需用户交互即可访问该帐户。

现在,这是我的代码

var opt = new ConfidentialClientApplicationoptions()
{
    ClientId = "xxx_clientid",TenantId = "xx_tenant_id",ClientSecret = "xxx_client_secret_value",RedirectUri = "http://localhost",};

var scopes = new string[] {
    "email","offline_access","https://outlook.office.com/IMAP.AccessAsUser.All",// Only needed for IMAP
    //"https://outlook.office.com/POP.AccessAsUser.All",// Only needed for POP
    //"https://outlook.office.com/SMTP.Send",// Only needed for SMTP
};

var app = ConfidentialClientApplicationBuilder.CreateWithApplicationoptions(opt).Build();
var authToken = await app.AcquiretokenForClient(scopes).ExecuteAsync(); // <--- Exception
var oauth2 = new SaslMechanismOAuth2(authToken.Account.Username,authToken.Accesstoken);

using (var client = new ImapClient(new ProtocolLogger("imapLog.txt")))
{
    client.Connect("outlook.office365.com",993,SecureSocketoptions.SslOnConnect);
    //client.AuthenticationMechanisms.Remove("XOAUTH2");
    client.Authenticate(oauth2);
    var inBox = client.InBox;
    inBox.Open(MailKit.FolderAccess.ReadOnly);
    Console.WriteLine("Total messages: {0}",inBox.Count);
    Console.WriteLine("Recent messages: {0}",inBox.Recent);
    client.disconnect(true);
}

运行代码我得到这个异常: Microsoft.Identity.Client.MsalServiceException: 'AADSTS70011: The provided request must include a 'scope' input parameter. The provided value for the input parameter 'scope' is not valid. The scope email offline_access https://outlook.office.com/IMAP.AccessAsUser.All is not valid.

我尝试按照 GitHub 上的指南进行操作: Using OAuth2 With Exchange

问题是我需要改用应用密码。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)