title: Exception using default SMTP credentials on Office365 - Client was not authenticated to send anonymous mail during MAIL FROM
body: <p>I'm using NLog to send logs as email with a custom mail target.  I am sending from my office365 account set up as the default in my web.config (of my main project) as follows:</p>
  
  <pre><code>  &lt;system.net&gt;
      &lt;mailSettings&gt;
        &lt;smtp deliveryMethod="Network" from="myusername@mydomain.com"&gt;
          &lt;network defaultCredentials="false" host="smtp.office365.com" port="587" userName="myusername@mydomain.com" password="mypassword" enableSsl="true" /&gt;
        &lt;/smtp&gt;
      &lt;/mailSettings&gt;
    &lt;/system.net&gt;
  </code></pre>
  
  <p>I override the Write method with my log target (in my NLog implementation package) as follows:</p>
  
  <pre><code>    protected override void Write(LogEventInfo logEvent) 
      { 
          try
          {
              using (var mail = new MailMessage())
              {
                  this.SetupMailMessage(mail, logEvent, this.Layout.Render(logEvent));
  
                  using (SmtpClient smtpClient = new SmtpClient())
                  {
                      smtpClient.UseDefaultCredentials = true;
                      smtpClient.Send(mail);
                  }
              }
          }
          catch (Exception exception)
          {
              throw new NLogRuntimeException("An error occurred when sending a log mail message.", exception);
          }
      }
  </code></pre>
  
  <p>When the system tries to send a mail from this account, the following <code>System.Net.Mail.SmtpException</code> is thrown:</p>
  
  <p>The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM</p>
  
  <p>I have quadruple checked the credentials and they are correct.  Does anyone know what else could be causing this exception?</p>
  
  <p><strong>UPDATE:</strong>  It turns out the CredentialCache.DefaultCredentials property is full of empty strings.  Yet, when I extract the settings manually using the below code I can get the settings from the web.config.  </p>
  
  <pre><code>SmtpSection settings = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
  smtpClient.Credentials = new NetworkCredential(settings.Network.UserName, settings.Network.Password);
  smtpClient.Host = settings.Network.Host;
  smtpClient.Port = settings.Network.Port;
  smtpClient.EnableSsl = settings.Network.EnableSsl;
  
  var creds = CredentialCache.DefaultCredentials;  // Is empty
  </code></pre>
  
  <p>I can use this as a workaround.  But what gives?  Why would the default credentials be empty?</p>