Can MailKit be used to send email using graph on azure

123 Views Asked by At

In the past azure (outlook 365) let users use SMTP to send email from apps, but in the past year this has changed and tokens granted by Micrsoft.Client.Identity cannot be used in the MailKit SmtpClient unless the users outlook365 account removes default azure security. I am not sure why they did this but we have been looking for a way to send emails through our apps.

We found this question and article on sending email using Microsoft graph, and this works. In the article the code sets up a json email message. I want to know if we can use MailKit to set up an email message and send using a MailKit method, or would we just need to serialize email created using MailKit into json and then do the PostAsync as the article does.

1

There are 1 best solutions below

0
Rukmini On

Yes, you can make use of Malkit to send mail like below:

Create an Azure AD application and assign below API permissions:

enter image description here

Grant access to the user:

Add-MailboxPermission -Identity "[email protected]" -User ServicePrincipalID -AccessRights FullAccess

For sample, I used client credential flow to generate the token by using below parameters:

https://login.microsoftonline.com/TenantID/oauth2/v2.0/token

client_id:ClientID
client_secret:ClientSecret
grant_type:client_credentials
scope:https://outlook.office.com/.default

enter image description here

By using the above token you call send mail like below:

var confidentialClientApplication = ConfidentialClientApplicationBuilder.Create (clientId)
    .WithAuthority ($"https://login.microsoftonline.com/{tenantId}/v2.0")
    .WithCertificate (certificate) // or .WithClientSecret (clientSecret)
    .Build ();
 
var scopes = new string[] {
    // For IMAP and POP3, use the following scope
    "https://ps.outlook.com/.default"

    // For SMTP, use the following scope
    // "https://outlook.office365.com/.default"
};

var authToken = await confidentialClientApplication.AcquireTokenForClient (scopes).ExecuteAsync ();
var oauth2 = new SaslMechanismOAuth2 (accountEmailAddress, authToken.AccessToken);

using (var client = new ImapClient ()) {
    await client.ConnectAsync ("outlook.office365.com", 993, SecureSocketOptions.SslOnConnect);
    await client.AuthenticateAsync (oauth2);
    await client.DisconnectAsync (true);
}

But it is suggested to make use of Microsoft Graph API to send mail for sing OAuth2 authentication. Refer this SO Thread by me

References:

Authenticate an IMAP, POP or SMTP connection using OAuth | Microsoft

MailKit/ExchangeOAuth2.md at master · jstedfast/MailKit · GitHub by jstedfast