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

4
我正在编写一个Windows控制台应用程序,用于从Office365上设置的特定电子邮件帐户读取电子邮件。账户已全部设置好,我们能够从Outlook收到电子邮件。该控制台应用程序将在远程服务器上按计划运行,并从特定的电子邮件中提取指定的附件,然后将这些电子邮件移到另一个文件夹中。我选择使用MimeKit的MailKit库,并已开始编写一个小型测试应用程序,如下所示:
当运行此代码时,调试器会在client.Authenticate处报错,报错信息是“AuthenticationException”。我在代码中使用的userName和passWord是正确的,且与我在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;
            }
        }
    }
}
3个回答

2

谢谢msestak,看起来这个电子邮件账户没有启用多因素身份验证,所以我看不到创建应用程序密码的选项。你认为在提供密码之前需要以某种方式加密我的密码吗? - rarpal
你需要提供端口993,并且可以使用SecureSocketOptions.Auto。 - terrencep

2
我改用Microsoft Exchange Web Service而不是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月使用了这段代码进行了快速测试。


1
使用Microsoft Exchange Web Service的完整示例? - Kiquenet
你也可以使用Microsoft Graph。 - West
1
注意:基本身份验证的关闭被推迟了一年,主要是由于Covid因素。关闭从2021年开始。主要关闭时间为2022年10月,只允许一些例外在那个时间点之后再延长一年或两年。 - SendETHToThisAddress

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接