Skip to content

Instantly share code, notes, and snippets.

@gscales
Created August 18, 2020 00:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gscales/57216f70aef4b79ff2c0a0053152d5d0 to your computer and use it in GitHub Desktop.
Save gscales/57216f70aef4b79ff2c0a0053152d5d0 to your computer and use it in GitHub Desktop.
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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment