How to find a sent Message Using MailMessage.InReplyTo

+1 vote
asked May 25, 2011 by Enrico (370 points)
edited May 26, 2011

Hi, i need to search the orginal message of a reply message. In the reply i've the InReplyTo attribute that contains the oraginal MessageId generate.

How can i searcf the original message using it MessageId?

I expect something about this but i didn't find nothing.

MailMessage ReplyMessage = "a read message"

MailMessage original = m_Imap.getMailMessageByMessageId(ReplyMessage.InReplyTo)

// do somethings

1 Answer

0 votes
answered May 26, 2011 by Jan Sotola (16,920 points)
edited May 26, 2011

The uniqueId used in Imap.GetMailMessage(uniqueId) method is another ID than the ID used in MailMessage.InReplyTo property.

There are three ways how to identify mail message (all of them are properties of the ImapMessageInfo object):

  • SequenceNumber - ordinal number of the message within a folder
  • UniqueId - string identifier of the message assigned by the IMAP server, unique within a folder
  • MessageId - ID generated by sender, used to easily associate replies with the original message

While the GetMailMessage() or GetMessageInfo() methods use the UniqueId, you need to search for the MessageID. You can do it using the following search query:

client.Search(ImapSearchParameter.Header("Message-Id", replyMessageId.Id));

The search query may not work on any server, but e.g. on Gmail it works all right.

Following more complex example shows, how to process replies of given MailMessage:

Imap client = new Imap();
MailMessage originalMessage;

// ...
// connect, login and get the original message
// ...

// process all replies of the message
foreach (MessageId replyMessageId in messageInfo.InReplyTo)
{
    // search for the messages with given MessageId
    ImapMessageCollection replies =
        client.Search(ImapSearchParameter.Header("Message-Id", replyMessageId.Id));
    // the replyMessageId is not guaranted to be unique but it usually is 
    // (so the search returns either 0 or 1 record)
    if (replies.Count > 0)
    {
        ImapMessageInfo replyMessageInfo = replies[0];
        // process the reply
        Console.WriteLine(" Reply: {0}\t{1}", replyMessageInfo.Date, replyMessageInfo.Subject);
    }
    else
        Console.WriteLine(" Reply not found");
}

Please note that the example don't set any IMAP folder. Usually, you will search the mail message within an Inbox folder, while the replies can be in Sent mail folder (or vice versa). Hence before searching for replies you should change the current folder - here is an exapmple for Gmail:

client.SelectFolder("[Gmail]/Sent Mail");
...