Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mailkit does not authenticate with credentials

I'm trying to send an email with Gmail account. I was able to send emails with yahoo, however, it doesn't work anymore, for some unknown reason. Which i posted a question about that as well, but not response.

In this instance, i'm trying to connect to a gmail account so that I can send emails, but with no luck, it fails after the Connect.

It connects successfully but doesn't authenticate at all, although I have the right credentials.

This is the error i'm getting. I want to mention that the credentials are right.

{"535: 5.7.8 Username and Password not accepted. Learn more at\n5.7.8  
  https://support.google.com/mail/?p=BadCredentials l17sm22879081wro.77 - gsmtp"}

Should I use any certificates or something? I'm sure I'm doing something wrong with the code.

The code

var message = new MimeMessage();

        message.From.Add(new MailboxAddress(contactModel.Name, "[email protected]"));
        // This needs to be put in a configuration file
        message.To.Add(new MailboxAddress("test", "[email protected]"));

        message.Subject = $"{contactModel.Name} contacted me!";
        message.Body = new TextPart("plain") {
            Text = contactModel.Message + 
            " Details of sender: " + contactModel.EmailAddress + ", " + contactModel.ContactNumber + " ," + contactModel.Name
        };

        using (var client = new SmtpClient())
        {
            try
            {
                if (!client.IsConnected)
                {
                    await client.ConnectAsync("smtp.gmail.com", 587,false);
                    client.AuthenticationMechanisms.Remove("XOAUTH2");
                }
                if (!client.IsAuthenticated)
                {
                    await client.AuthenticateAsync("[email protected]", "password");
                }

                await client.SendAsync(message);
                await client.DisconnectAsync(true);

                return "success";
            }
            catch (SmtpCommandException ex)
            {
                throw;
            }
            catch (SmtpProtocolException ex)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new Exception($"The email from {contactModel.EmailAddress} captured but not sent to the owner");
            }

        }

enter image description here

And I got this email in my inbox, how I can bypass this?

like image 629
Csibi Norbert Avatar asked Dec 17 '22 14:12

Csibi Norbert


1 Answers

What you need to do is to sign-in to your Google Mail account in a web browser, go to Settings, and then check "Enable less secure apps". I believe this url will get you there if you are already signed in: https://myaccount.google.com/lesssecureapps

like image 168
jstedfast Avatar answered Dec 26 '22 15:12

jstedfast