title: MailKit, Office 365 and OAUTH2: Problem in authentication of a server side app
body: <p>I have to build a .Net console application that runs on server side as a batch, and sends email to recipients using Office365 and MailKit.</p>
  <p>Our company has recently introduced MultiFactor Authentication; I have already rewrite an interactive app that let user to send email using MailKit and MFA, but I am not able to implement the same functionality in an unattended app.</p>
  <p>I already register the application on Microsoft Azure, create the Client Secret and implement the following class:</p>
  <pre><code>    public class Mailer {
      public async static void Send(string subject, string body) {
          string tenantID = &quot;abcdef&quot;;
          string clientId = &quot;ghilmn&quot;;
          string clientSecret = &quot;opqrst&quot;;
          string appName = &quot;MyApp&quot;;
  
          //clientSecret = Uri.EscapeDataString(clientSecret);
          //clientSecret = Uri.EscapeUriString(clientSecret);
  
          var MyConfidentialClientApplication = ConfidentialClientApplicationBuilder.Create(clientId)
              .WithClientSecret(clientSecret)
              .WithTenantId(tenantID)
              .Build();
  
          var scopes = new string[] {&quot;https://graph.microsoft.com/.default&quot;};
  
          try {
              var authToken = await MyConfidentialClientApplication.AcquireTokenForClient(scopes).ExecuteAsync();
  
              var oauth2 = new SaslMechanismOAuth2(appName, authToken.AccessToken);  //  SaslMechanismOAuth2(appName, authToken.AccessToken);
              var m_client = new SmtpClient(new ProtocolLogger(&quot;smtp.log&quot;));
              await m_client.ConnectAsync(&quot;outlook.office365.com&quot;, 587, SecureSocketOptions.StartTls);
              await m_client.AuthenticateAsync(oauth2);
          }
          catch (Exception ex) {
              Debug.WriteLine(ex.Message);
              // do nothing;
          }
          return;
  
      }
  </code></pre>
  <p>While the token seems to be correctly acquired (the authToken.AccessToken is not null), the</p>
  <blockquote>
  <p>await m_client.AuthenticateAsync(oauth2);</p>
  </blockquote>
  <p>generate the following error:</p>
  <pre><code>Eccezione generata: 'MailKit.Security.AuthenticationException' in System.Private.CoreLib.dll
  535: 5.7.3 Authentication unsuccessful [ZR0P278CA0036.CHEP278.PROD.OUTLOOK.COM]
  </code></pre>
  <p>Basically I don't understand</p>
  <ul>
  <li>if the SaslMechanismOAuth2 is the correct one to be invoked</li>
  <li>if yes, what userName shall I pass to the constructor of oauth2; i tried with AppName, AppID and even with user email, but with no success.</li>
  </ul>
  <p>Any hint will be appreciated, thanks in advance.</p>
  <p>Paolo</p>
  <p><strong>P.S.</strong> the interactive app that is working uses the PublicClientApplicationBuilder and the AcquireTokenInteractive calls, using the following code.</p>
  <pre><code>        public async Task  Connect_MFA() {
          
          var options = new PublicClientApplicationOptions {
              ClientId = &quot;abcd&quot;,
              TenantId = &quot;efgh&quot;,
              RedirectUri = &quot;https://login.microsoftonline.com/common/oauth2/nativeclient&quot;
          };
  
          var publicClientApplication = PublicClientApplicationBuilder
              .CreateWithApplicationOptions(options)
              .Build();
  
          var scopes = new string[] {
              &quot;email&quot;,
              &quot;offline_access&quot;,
              //&quot;https://outlook.office.com/IMAP.AccessAsUser.All&quot;, // Only needed for IMAP
              //&quot;https://outlook.office.com/POP.AccessAsUser.All&quot;,  // Only needed for POP
              &quot;https://outlook.office.com/SMTP.Send&quot;, // Only needed for SMTP
          };
  
          var authToken = await publicClientApplication.AcquireTokenInteractive(scopes).ExecuteAsync();
  
          var oauth2 = new SaslMechanismOAuth2(authToken.Account.Username, authToken.AccessToken);
  
          m_client = new SmtpClient(new ProtocolLogger(&quot;smtp.log&quot;));
          await m_client.ConnectAsync(&quot;outlook.office365.com&quot;, 587, SecureSocketOptions.StartTls);
          await m_client.AuthenticateAsync(oauth2);
      }
  </code></pre>