我试图实现OAUTH通过Outlook(Office 365)从各种内部开发的程序发送电子邮件。我已在Azure中创建了一个应用程序注册,并为其授予Mail.ReadWrite、Mail.Send和User.Read权限。我想我漏了一步。
我使用this article作为准则。
我已经添加了Mail.ReadWrite、Mail.Send和User.Read权限。我已经从Office365 ExchangeOnline添加了IMAP.AccessAsApp和SMTP.SendAsApp。此代码块:
private async void SendMailOAUTH(MemoryStream ms, string ServiceName, string DList)
{
string authority = $"https://login.microsoftonline.com/{tenantId}";
string[] scopes = { "https://graph.microsoft.com/.default" };
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority(authority)
.Build();
AuthenticationResult authResult = await app.AcquireTokenForClient(scopes).ExecuteAsync();
string accessToken = authResult.AccessToken;
// Create the attachment
System.Net.Mime.ContentType ct = new("application/vnd.ms-excel");
System.Net.Mail.Attachment attachment = new(ms, ct);
attachment.ContentDisposition!.FileName = ServiceName + ".xlsx";
// Create the email message
MailMessage serviceMail = new MailMessage(userEmail, DList)
{
Subject = ServiceName,
Body = "Please see the attached spreadsheet."
};
serviceMail.Attachments.Add(attachment);
// Create the SMTP client with OAuth2 authentication
SmtpClient smtpClient = new SmtpClient("smtp.office365.com", 587)
{
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(userEmail, accessToken),
TargetName = "STARTTLS/smtp.office365.com"
};
try
{
// Send the email
smtpClient.Send(serviceMail);
}
catch (Exception ex)
{
_ = ex.Message;
}
finally
{
// Dispose resources
smtpClient.Dispose();
serviceMail.Dispose();
attachment.Dispose();
}
}
调用smtpClient时产生此错误。发送:
“SMTP服务器需要安全连接,或者客户端未经过身份验证。服务器响应为:5.7.57客户端未经验证发送邮件。错误:535 5.7.139身份验证不成功,请求不符合成功身份验证的条件。请与管理员联系。[BY3PR05CA0036.namprd05.prod.outlook.com 2023-06-01T19:15:39.132Z 08DB625E632A34A0]”
我卡住了。有人能帮帮我吗?
我认为问题可能出在作用域上,所以我尝试了string[] scopes = {“https://outlook.office.com/.default“},但仍然得到相同的错误。
我已经检查了其他文章,并尝试了建议的补救措施,无济于事。
1条答案
按热度按时间bihw5rsg1#
尝试以下设置以阻止旧版身份验证: