title: How do I use Gmail's SMTP client to send an email to myself in C# without enabling access for less secure apps in Gmail settings?
body: <p>I'm working on an ASP.NET Web Forms app and I'm trying to programmatically  send an email to myself. I'm using Gmail's SMTP client, and all is well except that when I send my message, I get this error:</p>
  <blockquote>
  <p>&quot;System.Net.Mail.SmtpException: The SMTP server requires a secure
  connection or the client was not authenticated. The server response
  was: 5.5.1 Authentication Required. Learn more at&quot;</p>
  </blockquote>
  <p>If I go into my gmail account settings and enable an option that allows me to allow access for &quot;less secure apps&quot;, everything works fine. I'm wondering how I can send my email with having this option enabled.</p>
  <pre class="lang-cs prettyprint-override"><code>protected void sendEmail(object sender, EventArgs e)
  {
      var client = new SmtpClient(&quot;smtp.gmail.com&quot;, 587)
      {
          Credentials = new System.Net.NetworkCredential(&quot;myusername@gmail.com&quot;, &quot;mypassword&quot;),
          DeliveryMethod = SmtpDeliveryMethod.Network,
          EnableSsl = true
      };
      
      MailAddress from = new MailAddress(&quot;myusername@gmail.com&quot;, &quot;Torchedmuffinz&quot;);
      MailAddress to = new MailAddress(&quot;myusername@gmail.com&quot;, &quot;Torchedmuffinz&quot;);
      MailMessage message = new MailMessage(from, to);
      message.Subject = &quot;test&quot;;
      message.Body = &quot;test&quot;;
      Attachment attachFile = new Attachment(@&quot;pathtofile&quot;);
      message.Attachments.Add(attachFile);
  
      try { client.Send(message); }
      catch (Exception email_exception)
      {
          System.Diagnostics.Debug.WriteLine(email_exception);
      }
  }
  </code></pre>