C# mailkit 在收件箱为空时显示错误

C# mailkit shows error when inbox is empty

下面的代码运行良好,但代码将每 5000 毫秒检查一次,当收件箱文件夹为空时系统会显示错误。 我们需要每 5000 毫秒检查一次收件箱,即使它是空的我们也需要阅读它。

        using (var client = new ImapClient())
        {
            client.Connect(EXT_IMAP_SERVER, EXT_IMAP_PORT, true);

            client.Authenticate(EXT_USERNAME, EXT_PASSWORD);

            var inbox = client.Inbox;
            inbox.Open(FolderAccess.ReadWrite);
            var LAST_MSG = inbox.GetMessage (inbox.Count - 1);
          
            DATA = LAST_MSG.Subject;
        
            if(DATA != null); // this condition didn't solve our issue
            {
                inbox.AddFlags(inbox.Count - 1, MessageFlags.Deleted, true);
            }
        
            client.Disconnect(true);
        }

**ERROR:
System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. (Parameter 'index')**

不检查最后一条消息是否为空,而是检查 Count 条消息,如果它大于 0,则执行您需要执行的操作。

using (var client = new ImapClient())
{
    client.Connect(EXT_IMAP_SERVER, EXT_IMAP_PORT, true);
    client.Authenticate(EXT_USERNAME, EXT_PASSWORD);

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

    // THIS
    if(inbox.Count > 0) {
        var LAST_MSG = inbox.GetMessage (inbox.Count - 1);
        // .....
    }

    client.Disconnect(true);
}