Search code examples
c#smtpsmtpclient

SmtpException in System.Net.Mail.dll


Im trying to send an email with c#, like so:

public string SendEmail(string employeeEmail, string clientEmail, string subject, string message)
{    
     MailMessage mailMessage = new MailMessage(employeeEmail, clientEmail)
     {
          Subject = subject,
          Body = message,
          BodyEncoding = Encoding.UTF8,
          IsBodyHtml = true
     };

     SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
     NetworkCredential basicCredential1 = new NetworkCredential("email", "password");
     client.EnableSsl = true;
     client.UseDefaultCredentials = false;
     client.Credentials = basicCredential1;

     try
     {
          if (UserExists(employeeEmail))
          {
               if (objDAL.ClientExists(clientEmail))
               {
                    client.Send(mailMessage);
                    return "Email sent";
               }
               else
               {
                    return "Client email not found";
               }
          }
          else
          {
               return "Employee email not found.";
          }
     }
     catch
     {
          return "ERROR";
     }
}

But it throws a 'System.Net.Mail.SmtpException' in System.Net.Mail.dll in client.Send(mailMessage); and i have no idea why. I've been searching for an answer for a days... Can someone please help me understand whats going on ? Am i missing something ?


Solution

  • Regarding the exception that you are getting, you have to enable Less Secure Sign-In (or Less secure app access) in your google account.

    After sign into google account, go to:

    https://www.google.com/settings/security/lesssecureapps or https://myaccount.google.com/lesssecureapps

    and enable the option. Once you do this step, you should be able to send e-mails.