We need to send an email using Azure access token (using Oauth 2.0 Modern Authentication) using SMTP protocol in c# code.
We tried the below code to get the access token:
Nuget Package used: Microsoft.IdentityModel.Clients.ActiveDirectory
public static void GetAuthorizationToken()
{
Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential cc = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(ClientID, ClientSecret);
var context = new AuthenticationContext("">login.microsoftonline.com/" + TenantID);
var result = context.AcquireTokenAsync("">management.azure.com/", cc);
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the Access token");
}
AccessToken = result.Result.AccessToken;
}
Now we are trying to send an email using SMTP protocol, but mail is not sending with the below code:
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.From = new System.Net.Mail.MailAddress("santhosh.s@XXX.com", "Santhosh");
message.To.Add(new System.Net.Mail.MailAddress("varuns@XXX.com", "Varun"));
message.Subject = "Proof of Concept";
message.Body = "this is a email sent from project.";
SmtpClient client = new SmtpClient("smtp.office365.com", 587);
client.Timeout = 400000;
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.SendAsync(message, AccessToken);
Can anyone help on this by providing the source code to send an email using SMTP (using Oauth 2.0 Modern Authentication) ?