如何解决使用AppID和APPSecret验证SmtpClient,而不传递用户名和密码
我在c#控制台应用程序中具有以下SharePoint CSOM代码,以使用office 365管理员用户名和密码发送电子邮件:-
static private void sendemail(ClientContext context,string subject,string body,FieldUserValue[] to,string username,securestring passWord)
{
try
{
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress("sharepoint@***.com");
mail.Subject = subject;
mail.IsBodyHtml = true;
SmtpClient client = new SmtpClient("***-com.mail.protection.outlook.com",25);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(username,passWord);
client.EnableSsl = true;
mail.Body = body;
string approvalemailTo = "";
foreach (var t in to)
{
mail.To.Add(t.Email);
approvalemailTo = approvalemailTo + t.Email + ";";
}
client.Send(mail);
}
}
catch (Exception e)
{
}
}
但是为了使我的代码更安全,我如何使用AppID和APPSecret而不是通过用户名和密码来验证SmtpClient?
谢谢
解决方法
您的代码只是System.net.mail程序集中的标准SMTP代码,它不依赖于Sharepoint CSOM。如果要在SMTP中使用现代身份验证,则无法使用客户端凭据流https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow按照
此功能公告适用于交互式应用程序,以为IMAP和SMTP启用OAuth。目前,尚无计划使用客户端凭据流为非交互式应用程序启用IMAP和SMTP OAuth。为此,我们建议使用我们的Graph API。
如果要执行此操作,则需要使用Microsoft Graph API,这对您而言很简单。如果您要坚持使用SMTP并使用现代身份验证,则需要使用支持它的MailKit https://github.com/jstedfast/MailKit之类的东西,例如使用MSAL和Interactive Auth的简单示例
String ClientId = "20773535-6b8f-4f3d-8f0e-4b7710d79afe";
string UserName = "user@domain.com";
string scope = "https://outlook.office.com/SMTP.Send";
string redirectUri = "msal20773535-6b8f-4f3d-8f0e-4b7710d79afe://auth";
string From = "Fromouser@domain.com;
String To = "Touser@domain.com";
String SMTPServer = "smtp.office365.com";
Int32 SMTPPort = 587;
PublicClientApplicationBuilder pcaConfig = PublicClientApplicationBuilder.Create(ClientId)
.WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs);
pcaConfig.WithRedirectUri(redirectUri);
var TokenResult = await pcaConfig.Build().AcquireTokenInteractive(new[] { scope })
.WithPrompt(Prompt.Never)
.WithLoginHint(UserName).ExecuteAsync();
var message = new MimeMessage();
message.From.Add(MailboxAddress.Parse(From));
message.To.Add(MailboxAddress.Parse(To));
message.Subject = "Test";
message.Body = new TextPart("plain")
{
Text = @"Hey Joe"
};
using (var client = new SmtpClient())
{
client.Connect(SMTPServer,SMTPPort,SecureSocketOptions.StartTls);
var oauth2 = new SaslMechanismOAuth2(UserName,TokenResult.AccessToken);
client.Authenticate(oauth2);
await client.SendAsync(message);
client.Disconnect(true);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。