title: Send mail from office 365 for business in C#
body: <p>I tried sending mail in my ASP.NET CORE project by C#. I ran code in emulation (IIS Express) but I get an error: </p>
  
  <blockquote>
    <p>The SMTP server requires a secure connection or the client was not authenticated.</p>
  </blockquote>
  
  <p>Please can you help me?</p>
  
  <p>My code:</p>
  
  <pre><code>MailMessage msg = new MailMessage();
  msg.To.Add(new MailAddress("formail@mail.com", "John Doe"));
  msg.From = new MailAddress("frommail@mail.com", "Jane Doe");
  msg.Subject = "This is a Test Mail";
  msg.Body = "This is a test message using Exchange OnLine";
  msg.IsBodyHtml = true;
  
  SmtpClient client = new SmtpClient();
  client.UseDefaultCredentials = false;
  client.Credentials = new System.Net.NetworkCredential("frommail@mail.com", "Password");
  client.Port = 587; 
  client.Host = "smtp.office365.com";
  client.DeliveryMethod = SmtpDeliveryMethod.Network;
  client.EnableSsl = true;
  
  try
  {
      client.Send(msg);
      return Content("Message sent successfully");
  }
  catch (Exception ex)
  {
      return Content(ex.ToString());
  }
  </code></pre>
  
  <p>Full error:</p>
  
  <blockquote>
    <p>System.Net.Mail.SmtpException: 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 [AM3PR07CA0113.eurprd07.prod.outlook.com]</p>
  </blockquote>
  
  <p>Thank you very much.</p>
  
  <p>EDIT: 
  I used code from <a href="https://stackoverflow.com/questions/30342884/5-7-57-smtp-client-was-not-authenticated-to-send-anonymous-mail-during-mail-fr">this question</a>. But I get error </p>
  
  <blockquote>
    <p>System.Net.Sockets.SocketException (11001): No such host is known.
    My mail adress is me@gjb-spgs.cz. </p>
  </blockquote>
  
  <p>My new code:</p>
  
  <pre><code>var sClient = new SmtpClient("gjbspgs-cz.mail.protection.outlook.com");
                  var message = new MailMessage();
  
                  sClient.Port = 25;
                  sClient.EnableSsl = true;
                  sClient.Credentials = new NetworkCredential("me@gjb-spgs.cz", "Password");
                  sClient.UseDefaultCredentials = false;
  
                  message.Body = "Test";
                  message.From = new MailAddress("me@gjb-spgs.cz");
                  message.Subject = "Test";
                  message.To.Add(new MailAddress("someone@gmail.com"));
  
                  sClient.Send(message);
              }
              catch (Exception ex)
              {
                  Console.Write(ex.ToString());
              }
  </code></pre>