Home > database >  Read emails from "Outlook" using ImapClient not working In C#
Read emails from "Outlook" using ImapClient not working In C#

Time:12-23

I developed a console application about 3 years ago and hosted it on our production server.

That console application was reading emails constantly from "outlook (Exchange)". It was working fine but I'm not sure why it stopped working suddenly.

Right now I'm getting an error message "LOGIN Failed."

Here is the existing code which was working as expected before:

public static void GetUnread(string hostname, int port, string username, string password)
{
    using (var client = new ImapClient())
    {
        client.ServerCertificateValidationCallback = (s, c, h, e) => true;
        client.Connect(hostname, port, SecureSocketOptions.SslOnConnect);
        client.Authenticate(username, password);

        var inbox = client.GetFolder("Inbox");
        inbox.Open(FolderAccess.ReadOnly);
        foreach (var uid in inbox.Search(SearchQuery.New).OrderByDescending(x => x))
        {
            DBOperation.SaveLog("Info", "Receive Email", "Mail box count:"   Convert.ToString(inbox.Count));

            // Other code for read email messages.
        }
    }
}

Method Calling:

GetUnread("pop3.live.com", 993, "Account email", "Account password");

I also tried to research this error but I'm not sure how I can fix the same. Any type of help would be appreciated.

Thanks in advance!!!

CodePudding user response:

Finally I've resolved issue by changing existing code by OAUTH2.

I'm going to post solution so that might be helpful for someone. I just followed article given below and now I'm able to connect to mailbox and read emails correctly using C# code.

Article Link: https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-authenticate-an-ews-application-by-using-oauth

Thanks!

  • Related