Search code examples
emailimap

retrieve a single email from imap by message_id


I am using ruby's Net::IMAP object and I can retrieve a set of emails using either:

IMAP.all ..args..

Or

IMAP.find ..args..

But is there anyway of retrieving a specific email, preferably by the message-id header for example?

Is this possible or am I limited to all and find and trying to narrow the result set with better arguments?


Solution

  • I didn't understand what technology you're using with IMAP. However the IMAP Specification provides the ability to search by a variety of fields, including email headers. You can use the following IMAP command to retrieve the UID of an email with Message-Id <53513DD7.8090606@imap.local>:

    0005 UID SEARCH HEADER Message-ID <53513DD7.8090606@imap.local>
    

    This will then give you a response such as the following:

    * SEARCH 1
    0005 OK UID completed
    

    In my case the email with Message-Id <53513DD7.8090606@imap.local> was the first one, so the SEARCH command returned a matching UID of 1.

    You can then retrieve the message using a UID FETCH command, such as the following:

    0006 UID FETCH 1 BODY[]
    

    Naturally, if you know the UID in advance, you can skip the UID SEARCH step, but that depends on your application.