尝试使用 MailKit 阅读电子邮件时出现 OnImapProtocolException()

问题描述 投票:0回答:1

我正在使用 MailKit v. 4.4.0 从 IMAP 服务器读取电子邮件。我的代码如下:

DateTime deliveredAfterDate = ... some date value
using (var client = new ImapClient())
{
  client.Connect(_emailConfig.ImapServer, _emailConfig.ImapPort, true);
  client.Authenticate(_emailConfig.UserName, _emailConfig.Password);

  var inbox = client.Inbox;
  inbox.Open(FolderAccess.ReadOnly);

  var query = SearchQuery.DeliveredAfter(deliveredAfterDate);
  IList<UniqueId> emailIds = inbox.Search(query);
    
  foreach (var uid in emailIds)
  {    
      // Exception is thown HERE
      var message = inbox.GetMessage(uid);                                
      if (message == null)
      {
          continue;
      }

      // Save email in DB
      IncomingMail newMail = new IncomingMail()
      {
          MessageId = message.MessageId,
          Subject = message.Subject ?? string.Empty,
          FromName = message.From.Mailboxes.FirstOrDefault()?.Name ?? string.Empty,
          FromAddress = message.From.Mailboxes.FirstOrDefault()?.Address ?? string.Empty,
          Timestamp = message.Date.LocalDateTime, // .DateTime,
          TextBody = message.TextBody ?? string.Empty,
      };
      await repo.InsertMailAsync(newMail)
  }

  client.Disconnect(true);
}

上面的代码在工作服务内部执行。操作完成后,一分钟后重复整个过程。

它在大多数情况下都有效。电子邮件被正确读取并保存在我的数据库中。然而,我定期会遇到以下异常:

产生异常。呼叫者成员姓名:读取,呼叫者路径: D:Directorate\源协议Protocol.Service\Services\EmailReader.cs, 调用方行号:146 11:50:27 错误异常堆栈跟踪:位于 MailKit.Net.Imap.ImapEngine.OnImapProtocolException() 在 MailKit.Net.Imap.ImapEngine.Iterate() 在 MailKit.Net.Imap.ImapFolder.GetMessage(UniqueId uid,CancellationToken 取消令牌、ITransferProgress 进度)位于 eProtocol.Service.Services.EmailReader.Read() 中 D:Directorate\source Protocol Protocol.Service\Services\EmailReader.cs:line 88

11:50:27 ERROR FETCH 失败:发生内部错误。参考服务器 登录以获取更多信息。 [2024-03-15 11:50:27]

知道为什么会发生此异常吗?

c# .net email .net-core mailkit
1个回答
0
投票
  1. 我建议首先通过

    包围您的代码来处理异常
    try{}
    catch(Exception ex)
    {
        // Handle other exceptions
        Console.WriteLine("An error occurred: " + ex.Message);
    }
    
  2. 服务器端问题:IMAP 服务器本身可能存在问题,例如资源限制、网络问题或软件错误。这可能是暂时的,随着时间的推移可能会自行解决。

© www.soinside.com 2019 - 2024. All rights reserved.