0

Like the title says I'm having an issue sending Email to gmail through code.

The weird thing is that I have used this exact code in a previous project and it was working at the time but now its not working at all in any of the projects.

I'm posting my code here below:

 protected void ButtonSkicka_Click(object sender, EventArgs e)
    {
        try
        {
            MailMessage MailMessage = new MailMessage();
            MailMessage.From = new MailAddress("MyEmail@gmail.com");
            MailMessage.To.Add("MyEmail@gmail.com");
            MailMessage.Subject = TextBoxÄmne.Text;

            MailMessage.Body = "<b>Namn : </b>" + TextBoxNamn.Text + "<br />"
                + "<b> Email : </b>" + TextBoxEmail.Text + "<br />"
                + "<b> Meddelande : </b>" + TextBoxMedd.Text + "<br />";
            MailMessage.IsBodyHtml = true;

            SmtpClient SmtpClient = new SmtpClient("smtp.gmail.com", 587);
            SmtpClient.EnableSsl = true;
            SmtpClient.Credentials = new NetworkCredential("MyEmail@gmail.com", "Password");
            SmtpClient.UseDefaultCredentials = false;
            SmtpClient.Send(MailMessage);

            TextBoxNamn.Text = "";
            TextBoxEmail.Text = "";
            TextBoxÄmne.Text = "";
            TextBoxMedd.Text = "";

            LabelTack.Text = "Tack för ditt meddelande!";


        }

        catch (Exception ex)
        {
            LabelTack.Text = ex.ToString();
        }

I have enables less trusted apps and disabled 2 part security on my Gmail account.

Here is the error im getting:

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. 
oOMelon
  • 97
  • 2
  • 8

1 Answers1

1

Firstly, the SmtpClient.Credentials should be declared after the UseDefaultCredentials is set to false.

SmtpClient.UseDefaultCredentials = false;
SmtpClient.Credentials = new NetworkCredential("MyEmail@gmail.com", "Password");

On your Gmail security tab, set "Allow less secure applications" to true.

Also, make sure 2 factor authentication is disabled. If it is enabled, you need to create an application-specific password for your application to allow login.

If this fails, try changing the password, as sometimes google will update their password policy and if a password is deemed to fail the policy the login will be prevented. (source https://stackoverflow.com/a/4931560/1666620)

Finally, you should wrap your SMTPClient declaration in a using statement to ensure proper disposal after use.

Community
  • 1
  • 1
user1666620
  • 4,800
  • 18
  • 27