Office 365 SMTP登录与应用程序密码使用c#



我的c# WPF程序在我们的Office 365公司帐户中实施双因素身份验证之前成功进行了身份验证并发送了邮件。我使用SmtpClient库,但现在我必须找到另一个解决方案,因为它不再工作了。我找不到O365应用程序密码的任何工作示例。有人能帮我解决这个问题吗?

我已经找到解决办法了。

似乎有一些配置阻止Azure AD上的遗留身份验证(尝试在google上查找Block legacy authentication条件访问策略)。此配置可能会阻止所有通过SMTP的访问。

然而,在我的研究过程中,我后来切换到使用微软API,它像一个魅力。我可以推荐它。下面是关于如何使用它的更详细的信息。在我看来,原因是整个IT世界都在缓慢地(或迅速地?)向更安全的技术移动,并花费精力让SMTP与2FA一起工作,对我来说似乎是浪费时间。因此,我在这个过程中停止了工作,在租户上启用了2FA,并实现了到API的连接。在我看来,这是未来的解决方案。至少再过几年。希望。

我特别使用了Microsoft Graph REST API(文档在这里)。在Azure上,您需要转到活动目录,注册一个新应用程序,设置应用程序权限并创建客户端密钥。对于API,您需要租户ID、应用ID和生成的客户端密钥。

在c#项目中,您需要安装NuGet包Azure。IdentityMicrosoft.Graph.

下面的代码在上工作。. NET Core 3.1。NET 5.0,但我想它会像一个魅力也。. NET 6.0(未测试).

下面是关于如何使用API的部分代码(简化):
public async Task SendEmail(string senderEmail, string recipientEmail, string messageSubject, string messageBody)
{
// The client credentials flow requires that you request the
// /.default scope, and preconfigure your permissions on the
// app registration in Azure. An administrator must grant consent
// to those permissions beforehand.
var scopes = new[] { "https://graph.microsoft.com/.default" };
// using Azure.Identity;
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = "your tenant ID from Azure will be right here";
// At Azure->Azure Active Directory->App Registrations->(your app) you can find all the information about your registered app.
// ID used here is "Application (client) ID" what you can see at this app page in Azure.
//
// Notice also that used App needs to have setup proper privileges in (Azure->Azure Active Directory->App Registration->(your app)->API permissions)
// Necessary privileges for this method and email sending are following privileges:
//     Permission type                             Permissions (from least to most privileged)
//     Delegated(work or school account)           [Mail.Send]
//     Delegated(personal Microsoft account)       [Mail.Send]
//     Application                                 [Mail.Send]
var azureActiveDirectoryAppClientId = "your app client ID from Azure will be right here";
// At (Azure->Azure Active Directory->App Registrations->(your app)->Certificates & secrets) you can manage credentials here.
// You can find ClientSecret here at mentioned path. 
// Be aware that this credentials can not be valid for more than 24 months.
var azureActiveDirectoryAppClientSecret = "your client secret from Azure will be right here";
// https://learn.microsoft.com/dotnet/api/azure.identity.clientsecretcredential
var clientSecretCredential = new ClientSecretCredential(tenantId,
azureActiveDirectoryAppClientId, azureActiveDirectoryAppClientSecret, options);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

var message = new Message
{
Subject = messageSubject,
Body = new ItemBody
{
ContentType = BodyType.Html,
Content = messageBody
},
ToRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = recipientEmail
}
}
}
};
await graphClient.Users[senderEmail].SendMail(message, null).Request().PostAsync();
}

此外,在代码graphClient.Users[*]中,您可以直接使用Azure的用户ID(在'*' char的位置)。

希望能有所帮助。我更多地关注代码片段,因为它可以表示很多内容,并且可以非常快速地重用它。

整个解决方案最终似乎是微不足道的。最难的部分在我看来是找到所有的信息。

关于使用Graph API的另一个答案对我或大多数人来说不是一个选择,因为你不能在免费帐户上向外部发送邮件,并且需要你从azure免费升级到高级,否则你必须通过邮件将你托管的服务器添加到白名单中,否则所有邮件都会在每个人的outlook上被阻止,包括你发送的smtp邮件地址

所以要在office 365 SMTP中做到这一点我需要做的是使用下面的函数

public static void SendEmail(string pToEmail, string pCC, string pFromEmail,
string pSubject, string pBody, Boolean pIsHTML, string pSMTP, string pUser, string pPassword)
{
//create the mail message
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
MailMessage mail = new MailMessage(pFromEmail, pToEmail);
mail.Subject = pSubject;
mail.IsBodyHtml = pIsHTML;
mail.Body = pBody;
if (pCC != "")
{
mail.CC.Add(pCC);
}
SmtpClient smtp = new SmtpClient(pSMTP);
smtp.EnableSsl = true;
smtp.Port = 25;

smtp.UseDefaultCredentials = false;
if (pUser != "")
{
System.Net.NetworkCredential smtpUser = new System.Net.NetworkCredential(pUser, pPassword);
smtp.Credentials = smtpUser;
}
smtp.Send(mail);
mail.Dispose();
smtp = null;
mail = null;
}

然后我必须提供mx给pSMTP

get this from

步骤2:查找电子邮件和更多的MX记录值在Microsoft 365管理中心,转到Settings>域页面。在域页面,选择您的域。

选择"管理DNS",选择"更多选项">添加您自己的DNS并选择继续查看要添加的DNS记录。

您将希望在进行更改时保持此信息可用在你的DNS主机,所以你可以复制和粘贴这些值。

页面上列出的DNS记录组取决于您的

转到添加DNS记录以连接您的域,然后按照步骤到在你的DNS主机网站上添加记录。

按以下步骤创建在您的DNS主机记录。

https://learn.microsoft.com/en-us/microsoft-365/admin/get-help-with-domains/information-for-dns-records?view=o365-worldwide

然后可以使用应用程序密码(也只适用于端口25)

相关内容

最新更新