Search code examples
c#outlookmailkit

How deal with MailKit.Security.AuthenticationException: 'LOGIN failed.'


I'm trying to read an email from my mailbox using the MailKit library. Unfortunately the program throws this MailKit.Security.AuthenticationException: 'LOGIN failed.' The credentials match (I tried to log in through the browser). I'm trying to read an email from my mailbox using the MailKit library. Unfortunately the program throws this

MailKit.Security.AuthenticationException: 'LOGIN failed.'

I would be grateful for any help, I don't know what to do. I googled, tried this client.Connect("imap.outlook.com", 993, SecureSocketOptions.None); But nothing came up when I changed SecureSocketOptions to Auto, the same exception was thrown

using (var client = new ImapClient())
            {
                using (var cancel = new CancellationTokenSource())
                {
                    client.Connect("imap.outlook.com", 993, true);

                    
                    //client.AuthenticationMechanisms.Remove("XOAUTH");

                    client.Authenticate("[email protected]", "password", cancel.Token);

                    
                    var inbox = client.Inbox;
                    inbox.Open(FolderAccess.ReadOnly, cancel.Token);

                    Console.WriteLine("Total messages: {0}", inbox.Count);
                    Console.WriteLine("Recent messages: {0}", inbox.Recent);

                   
                    for (int i = 0; i < inbox.Count; i++)
                    {
                        var message = inbox.GetMessage(i, cancel.Token);
                        Console.WriteLine("Subject: {0}", message.Subject);
                    }

                   
                    var query = SearchQuery.DeliveredAfter(DateTime.Parse("2013-01-12"))
                        .And(SearchQuery.SubjectContains("MailKit"))
                        .And(SearchQuery.Seen);

                    foreach (var uid in inbox.Search(query, cancel.Token))
                    {
                        var message = inbox.GetMessage(uid, cancel.Token);
                        Console.WriteLine("[match] {0}: {1}", uid, message.Subject);
                    }

                    client.Disconnect(true, cancel.Token);
                }
            }

Solution

  • The AuthenticationException has nothing to do with SSL and therefor is not a problem with client.Connect(...). It's a problem with client.Authenticate (username, password)

    Microsoft's public email servers no longer allow the use of usernames and passwords. They now require authentication via OAuth2.

    For information about how to authenticate using OAuth2, see the MailKit docs: https://github.com/jstedfast/MailKit/blob/master/ExchangeOAuth2.md