简体   繁体   中英

C# MailKit get messages conversation/replies inside treeview

i'm trying to replicate the view of a mailbox, i try to use references and threads but don't work, somethimes thread has uniqueid null.

   foreach (var rfr in Message.References ?? new MimeKit.MessageIdList())
        {
            var _uids = Imap.Inbox.Search(SearchQuery.HeaderContains("Message-Id", rfr));

            if (_uids.Count > 0)
            {
                var _messages = Imap.Inbox.Fetch(_uids.ToList(), MessageSummaryItems.Envelope | MessageSummaryItems.Flags).OrderByDescending(o => o.Date);

                foreach (var msg in _messages)
                {
                    _Added.Add(msg.UniqueId);

                    RequestModel _model = new RequestModel
                    {
                        Address = msg.Envelope.From.Mailboxes.FirstOrDefault().Name ?? msg.Envelope.From.Mailboxes.FirstOrDefault().Address,
                        Subject = msg.Envelope.Subject,
                        Date = msg.Date.ToLocalTime().ToString(),
                        IsSeen = msg.Flags.Value.HasFlag(MailKit.MessageFlags.Seen),
                        Childs = new List<Scratch.MainWindow.RequestModel>(),
                    };

                    _retValue.Add(_model);
                }
            }
        }

var _messages = _imapClient.Inbox.Fetch(_uids.ToList(), MessageSummaryItems.Envelope | MessageSummaryItems.Flags | MessageSummaryItems.References).OrderByDescending(o => o.Date).Take(50);
            var _threads = MessageThreader.Thread(_messages, ThreadingAlgorithm.References);

The MessageThreader class uses the References (which contin a list of Message-Id values tracing back to the root of the thread) in order to construct the tree of messages. Obviously, if the list of message summaries that you give to the MessageThreader are missing some of those references, then the returned tree will have some empty nodes. This is why some of said nodes have a null UniqueId value.

FWIW, a few tips for you:

  1. Don't do _uids.ToList() - _uids is already an IList<UniqueId> , why duplicate it for no reason?

  2. It's more efficient to use the orderBy argument to MessageThreader .

Like this:

var orderBy = new OrderBy[] { OrderBy.ReverseDate };
var threads = MessageThreader.Thread (summaries, ThreadingAlgorithm.References, orderBy);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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