Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read Office365 emails from Exchange Server using .Net C# IMAP client

I am writing a Windows Console App to read emails from a specially setup email account on Office365. The account is all setup and we are able to receive emails from Outlook. The Console App is is will run on a schedule from a remote server and extract specific attachments from specific emails, then move those emails to another folder. I have chosen to use the MailKit library from MimeKit and have started to code a small test app which I am listing below:

When ran the debugger on this code, I hit an error at client.Authenticate with the exception raised as "AuthenticationException". The userName and passWord I am using in my code is correct and the same I use in Outlook. Am I doing the basics right here ? Can I provide passWord in plain text or is there a specific format I need to use ? Please let me know if I have not provided all the info hear and I will get them and post here.

using MailKit.Net.Imap;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace CAppHarvestEmail
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var userName = "[email protected]";
                var passWord = "mybipassword";
                using (var client = new ImapClient())
                {
                    client.Connect("outlook.office365.com", true);
                    client.AuthenticationMechanisms.Remove("XOAUTH2");
                    client.Authenticate(userName, passWord);
                    var inbox = client.Inbox;
                    inbox.Open(MailKit.FolderAccess.ReadOnly);
                    Console.WriteLine("Total messages: {0}", inbox.Count);
                    Console.WriteLine("Recent messages: {0}", inbox.Recent);
                    client.Disconnect(true);
                }
            }
            catch (Exception e)
            {
                throw;
            }
        }
    }
}
like image 957
rarpal Avatar asked Sep 14 '25 02:09

rarpal


1 Answers

You need to generate app password for your application https://support.office.com/en-us/article/create-an-app-password-for-office-365-3e7c860f-bda4-4441-a618-b53953ee1183 and change line

client.Connect("outlook.office365.com", 993, SecureSocketOptions.SslOnConnect);
like image 84
Matija Sestak Avatar answered Sep 15 '25 16:09

Matija Sestak