繁体   English   中英

使用 .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 中使用的相同。 我在这里做的是基础吗? 我可以提供纯文本密码还是需要使用特定格式? 如果我没有提供所有信息,请告诉我,我会得到它们并在这里发布。

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);

我求助于使用 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();
}

参考

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM