Access shared/delegate mailbox of Office 365

There are 2 ways of accessing a shared mailbox in Office 365: first -using regular IMAP authentication and a second one – using OAuth 2.0.

Shared mailbox – basic authentication

Make sure basic authentication is turned on:

Try authenticating to users’ regular mailbox with his credentials to check if basic authentication works and the user/password is correct:

client.UseBestLogin("AlexW@example.com", "AlexWPassword");

Access the shared mailbox

Use the following user format:

Username@DomainName\Shared@DomainName

You must use Login method:

client.Login(@"AlexW@example.com\invoices@example.com", "AlexWPassword"); 

-or-

alternatively you may use LoginPlain method:

client.LoginPlain("invoices@example.com", "AlexW@example.com", "AlexWPassword");

Don’t use UseBestLogin for Office365 shared mailboxes and basic authentication.

The reason is Office  365 advertises LOGIN PLAIN as a preferred login method and UseBestLogin chooses to use it. However Office 365 does not recognize Username@DomainName\Shared@DomainName user pattern when using LOGIN PLAIN. For Office 365 to accept a LOGIN PLAIN to a shared mailbox, you need to provide all 3 parameters separately: shared mailbox, user and user password – use LoginPlain to do that.

Shared mailbox – OAuth 2.0

It is much simpler with OAuth. Use any of the available OAuth 2.0 flows:

https://www.limilabs.com/blog/oauth2-password-grant-office365-exchange-imap-pop3-smtp

https://www.limilabs.com/blog/oauth2-office365-exchange-imap-pop3-smtp

When you’ve obtained an access token you simply use it to access shared mailbox:

string accessToken = result.AccessToken;

using (Imap client = new Imap())
{
    client.ConnectSSL("outlook.office365.com");
    client.LoginOAUTH2("invoices@example.com", accessToken);

    client.SelectInbox();

    List<long> uids = imap.Search(Flag.Unseen);
    foreach (long uid in uids)
    {
        var eml = imap.GetMessageByUID(uid)
        IMail email = new MailBuilder().CreateFromEml();
        string subject = email.Subject);
    }
    client.Close();
}

Tags: , ,

Questions?

Consider using our Q&A forum for asking any questions.