使用C# MailKit实现无交互Windows Service代发微软邮箱邮件
无交互实现MailKit代发微软企业账号邮件(基于OAuth2 ROPC流程)
可以通过OAuth2的资源所有者密码凭证(ROPC)流程实现无交互代发,前提是你持有的用户账号满足以下条件:
- 未启用多因素认证(MFA)
- 属于Azure AD或已同步到Azure AD的企业账号(不支持微软个人账户)
一、Azure应用注册配置
- 登录Azure门户,进入你的应用注册,在API权限页面:
- 添加权限 → 选择
Office 365 Exchange Online→ 勾选委托权限下的SMTP.Send - 点击授予管理员同意(企业租户下必须完成此步骤,否则无法获取令牌)
- 添加权限 → 选择
- 在认证页面:
- 启用允许公共客户端流(ROPC属于公共客户端模式,无需客户端密钥)
二、C#代码实现
1. 安装依赖NuGet包
Install-Package MailKit Install-Package Microsoft.Identity.Client
2. 获取OAuth2访问令牌
using Microsoft.Identity.Client; public static async Task<string> GetSmtpOAuthToken(string tenantId, string clientId, string username, string password) { var publicClient = PublicClientApplicationBuilder .Create(clientId) .WithTenantId(tenantId) .WithAuthority(AzureCloudInstance.AzurePublic, tenantId) .Build(); // SMTP.Send的权限范围 var scopes = new[] { "https://outlook.office365.com/SMTP.Send" }; var authResult = await publicClient.AcquireTokenByUsernamePassword(scopes, username, password) .ExecuteAsync(); return authResult.AccessToken; }
3. 使用MailKit发送邮件
using MailKit.Net.Smtp; using MailKit.Security; using MimeKit; public static async Task SendEmail(string token, string fromEmail, string toEmail, string subject, string htmlBody) { var message = new MimeMessage(); message.From.Add(new MailboxAddress("发件人", fromEmail)); message.To.Add(new MailboxAddress("收件人", toEmail)); message.Subject = subject; message.Body = new TextPart("html") { Text = htmlBody }; using var smtpClient = new SmtpClient(); // 连接Office 365 SMTP服务器 await smtpClient.ConnectAsync("outlook.office365.com", 587, SecureSocketOptions.StartTls); // 用OAuth2令牌认证 await smtpClient.AuthenticateAsync(new SaslMechanismOAuth2(fromEmail, token)); await smtpClient.SendAsync(message); await smtpClient.DisconnectAsync(true); }
4. 调用示例
var tenantId = "你的租户ID"; var clientId = "你的应用注册客户端ID"; var username = "用户企业邮箱账号"; var password = "用户账号密码"; var token = await GetSmtpOAuthToken(tenantId, clientId, username, password); await SendEmail(token, username, "recipient@example.com", "测试邮件", "<h1>无交互代发测试</h1>");
三、注意事项
- ROPC流程存在密码泄露风险,微软不推荐在新应用中使用,但这是当前无交互且持有用户密码场景下的可行方案
- 确保Windows Service服务器能访问Azure AD认证端点(
login.microsoftonline.com)和Office 365 SMTP服务器(outlook.office365.com) - 如果用户账号启用MFA,此方案不可用,需改用应用权限的SMTP.Send流程(需管理员同意,代发时使用应用身份而非用户身份)
内容的提问来源于stack exchange,提问作者Haggo
相关产品推荐
相关产品推荐

