Naveen
Naveen

Reputation: 25

Mailkit authenticate attempt results in GMail SMTP error

I am using following code to send mail through google authorization using accessToken, but i am getting error "AuthenticationInvalidCredentials: 5.7.8 Username and Password not accepted. Learn more at

5.7.8 https://support.google.com/mail/?p=BadCredentials g26sm3048778pfk.173 - gsmtp"

                if (!string.IsNullOrEmpty(Email))
               {
               Msg.From.Add(new MimeKit.MailboxAddress(Name, Email));
                //MimeKit.MimeMessage Msg = new MimeKit.MimeMessage();
                //Msg.From.Add(new MimeKit.MailboxAddress(Email, Name));
                //Msg.To.Add(new MimeKit.MailboxAddress((string)message.To));
                using (var client = new MailKit.Net.Smtp.SmtpClient())
                {
                    var credentials = new System.Net.NetworkCredential(Email, AccessToken);
                    // Note: if the server requires SSL-on-connect, use the "smtps"
                    // protocol instead
                    var uri = new Uri("smtp://smtp.gmail.com:587");

                    using (var cancel = new System.Threading.CancellationTokenSource())
                    {
                        var options = MimeKit.FormatOptions.Default.Clone();

                        if (client.Capabilities.HasFlag(MailKit.Net.Smtp.SmtpCapabilities.UTF8))
                            options.International = true;
                        client.Connect(uri, cancel.Token);
                        client.Authenticate(credentials, cancel.Token);
                        client.Send(options, Msg, cancel.Token);
                        client.Disconnect(true, cancel.Token);
                        flag = true;
                    }
                }
            }

Upvotes: 2

Views: 2089

Answers (1)

jstedfast
jstedfast

Reputation: 38538

If you want to use OAuth2 authentication, starting with MailKit 2.0, you need to use the following approach (because the normal Authenticate() method no longer tries XOAUTH2):

var oauth2 = new SaslMechanismOAuth2 (credentials);
client.Authenticate (oauth2);

Upvotes: 1

Related Questions