使用 .Net C# IMAP 客户端从 Exchange Server 读取 Office365 电子邮件

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

我正在编写一个 Windows 控制台应用程序来读取来自 Office365 上专门设置的电子邮件帐户的电子邮件。该帐户已全部设置完毕,我们可以接收来自 Outlook 的电子邮件。控制台应用程序将 运行 根据远程服务器的时间表从特定电子邮件中提取特定附件,然后将这些电子邮件移动到另一个文件夹。我选择使用 MimeKit 中的 MailKit 库,并开始编写我在下面列出的小型测试应用程序:

当 运行 调试器对此代码进行调试时,我在 client.Authenticate 遇到了一个错误,异常引发为 "AuthenticationException"。我在代码中使用的用户名和密码是正确的,与我在 Outlook 中使用的相同。我在这里做基础吗?我能否以纯文本形式提供密码,或者是否需要使用特定格式?如果我没有提供所听到的所有信息,请告诉我,我会在此处获取它们和 post。

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 = "bi@mydomain.co";
                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;
            }
        }
    }
}

您需要为您的应用程序生成应用程序密码https://support.office.com/en-us/article/create-an-app-password-for-office-365-3e7c860f-bda4-4441-a618-b53953ee1183并更改线路

client.Connect("outlook.office365.com", 993, SecureSocketOptions.SslOnConnect);

提供端口 993 你可以使用 SecureSocketOptions.Auto

我使用 Microsoft Exchange Web 服务而不是 IMAP。

示例:

using System;
using Microsoft.Exchange.WebServices.Data;



ExchangeService _service;

Console.WriteLine("Registering Exchange connection");

_service = new ExchangeService
{
    Credentials = new WebCredentials(username, password)
};

// This is the office365 webservice URL
_service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");

PropertySet propSet = new PropertySet(BasePropertySet.FirstClassProperties);
propSet.Add(ItemSchema.MimeContent);
propSet.Add(ItemSchema.TextBody);

foreach (EmailMessage email in _service.FindItems(WellKnownFolderName.Inbox, new ItemView(10)))
{
    var message = EmailMessage.Bind(_service, email.Id, propSet);

    Console.WriteLine("Email body: " + message.TextBody);
    Console.WriteLine();
}

Reference

注意:这似乎是 to be deprecated。另外,我不确定这是否使用基本身份验证。我想不会,因为它应该在 2020 年 10 月之后停止工作,而我刚刚在 2021 年 7 月使用此代码进行了快速测试。