使用Rebex通过SMTP连接Office365时出现登录错误
Office365 SMTP OAuth2.0认证失败(错误535)
已完成Office365环境配置,通过Rebex库+C#实现了EWS、IMAP协议的OAuth2.0收发邮件,但SMTP协议登录时返回**Authentication unsuccessful (535)**错误,以下是具体代码和错误信息:
通用OAuth2.0令牌获取代码(正常工作)
string[] scopes = new[] { "https://outlook.office365.com/.default", "openid", "email", "profile" }; // 初始化机密客户端应用实例 var cca = ConfidentialClientApplicationBuilder .Create(clientId) .WithClientSecret(clientSecretValue) .WithTenantId(tenantId) .Build(); // 获取OAuth2.0访问令牌 AuthenticationResult result = await cca.AcquireTokenForClient(scopes).ExecuteAsync(); string accessToken = result.AccessToken;
EWS版本代码(运行正常)
using (var client = new Rebex.Net.Ews()) { client.Connect("outlook.office365.com", SslMode.Implicit); client.Settings.Impersonation = new EwsImpersonation() { SmtpAddress = emailAddress }; if (!client.IsAuthenticated) client.Login(accessToken, EwsAuthentication.OAuth20); var list = client.GetMessageList(EwsFolderId.Inbox); client.SendMessage(mail); client.Disconnect(); }
IMAP版本代码(运行正常)
using (var client = new Imap()) { client.Connect("outlook.office365.com", SslMode.Implicit); string pattern2 = string.Format("user={0}{1}auth=Bearer {2}{1}{1}", emailAddress, '\x1', accessToken); string token2 = Convert.ToBase64String( Encoding.ASCII.GetBytes(pattern2)); client.Login(token2, ImapAuthentication.OAuth20); }
SMTP版本代码(返回535错误)
using (var client = new Smtp()) { // 也尝试过outlook.office365.com client.Connect("smtp.office365.com", SslMode.Explicit); string pattern2 = string.Format("user={0}{1}auth=Bearer {2}{1}{1}", emailAddress, '\x1', accessToken); string token2 = Convert.ToBase64String(Encoding.ASCII.GetBytes(pattern2)); client.Login(emailAddress, token2, Rebex.Net.SmtpAuthentication.OAuth20); client.Send(mail); client.Disconnect(); }
错误日志
[date] ERROR Smtp(1)[8] Info:
Rebex.Net.SmtpException: Authentication unsuccessful
[foo.foo.PROD.OUTLOOK.COM] (535). in
Rebex.Net.Smtp.rozhm(String p0, String p1, SmtpAuthentication p2,
GssApiProvider p3) in Rebex.Net.Smtp.hcpew(String p0, String p1,
SmtpAuthentication p2)
排查与解决建议
检查Azure AD应用权限配置
- 确保为应用注册添加了SMTP.Send应用权限(属于Office 365 Exchange Online权限组),且已完成管理员授权。注意必须是「应用权限」而非「委派权限」,因为当前使用的是客户端凭证流(
AcquireTokenForClient)。
- 确保为应用注册添加了SMTP.Send应用权限(属于Office 365 Exchange Online权限组),且已完成管理员授权。注意必须是「应用权限」而非「委派权限」,因为当前使用的是客户端凭证流(
简化SMTP认证调用方式
- Rebex SMTP客户端已封装OAuth2.0认证逻辑,无需手动构造Base64格式令牌,直接传入原始accessToken即可,避免格式错误:
using (var client = new Smtp()) { client.Connect("smtp.office365.com", 587, SslMode.Explicit); client.Login(emailAddress, accessToken, SmtpAuthentication.OAuth20); client.Send(mail); client.Disconnect(); }
- Rebex SMTP客户端已封装OAuth2.0认证逻辑,无需手动构造Base64格式令牌,直接传入原始accessToken即可,避免格式错误:
验证令牌有效性
- 使用令牌解析工具检查accessToken,确认
aud(受众)为https://outlook.office365.com,且roles字段包含SMTP.Send权限。
- 使用令牌解析工具检查accessToken,确认
确认SMTP端点与端口
- Office365 SMTP的标准配置为:端点
smtp.office365.com,端口587,加密方式SslMode.Explicit,确保端口未被防火墙/代理拦截。
- Office365 SMTP的标准配置为:端点
内容的提问来源于stack exchange,提问作者Emanuele
相关产品推荐
相关产品推荐

