Create Gmail url-ID via IMAP

This is Gmail link that points to certain conversation (entire thread):

https://mail.google.com/mail/u/0/#inbox/13216515baefe747

“13216515baefe747” is the Gmail thread-ID in hex.

Here’s the code that:

  1. Selects “All Mail” folder
  2. Gets the newest message UID
  3. Obtains Gmail thread ID for this message (X-GM-THRID)
  4. Converts it to hex
  5. Creates the url that points to the Gmail conversation
// C# version
 
using (Imap client = new Imap())
{
    client.ConnectSSL("imap.gmail.com");
    client.UseBestLogin("pat@gmail.com", "app-password");
 
    // Select 'All Mail' folder
    CommonFolders common = new CommonFolders(
        client.GetFolders());
    client.Select(common.AllMail);
 
    // get IMAP uid of the newest message
    long lastUid = client.GetAll().Last();
 
    // get message info
    MessageInfo info = client.GetMessageInfoByUID(lastUid);
 
    // extract Gmail thread ID
    decimal threadId = info.Envelope.GmailThreadId;
    string threadIdAsHex = threadId.ToString("x");
 
    // create url
    string url = string.Format(
        "https://mail.google.com/mail/u/0/#inbox/{0}",
        threadIdAsHex);
 
    Console.WriteLine(url);
 
    client.Close();
}
' VB.NET version
 
Using client As New Imap()
    client.ConnectSSL("imap.gmail.com")
    client.UseBestLogin("pat@gmail.com", "app-password")
 
    ' Select 'All Mail' folder
    Dim common As New CommonFolders(client.GetFolders())
    client.Select(common.AllMail)
 
    ' get IMAP uid of the newest message
    Dim lastUid As Long = client.GetAll().Last()
 
    ' get message info
    Dim info As MessageInfo = client.GetMessageInfoByUID(lastUid)
 
    ' extract Gmail thread ID
    Dim threadId As Decimal = info.Envelope.GmailThreadId
    Dim threadIdAsHex As String = threadId.ToString("x")
 
    ' create url
    Dim url As String = String.Format( _
        "https://mail.google.com/mail/u/0/#inbox/{0}", _
        threadIdAsHex)
 
    Console.WriteLine(url)
 
    client.Close()
End Using

Here you can find some more information about how to search by X-GM-THRID and all other Gmail IMAP extensions.

Tags:      

Questions?

Consider using our Q&A forum for asking any questions.

3 Responses to “Create Gmail url-ID via IMAP”

  1. Gmail extensions in Mail.dll Says:

    […] Create Gmail url-ID via IMAP […]

  2. Anders Rune Jensen Says:

    The hexification need to be:

    string threadIdAsHex = threadId.ToString(“x”);

    and not:

    string threadIdAsHex = threadId.ToString(“X”);

  3. Limilabs support Says:

    Thanks – Corrected!
    It seems Gmail doesn’t like upper case letters.