Search code examples
javajakarta-mailimap

Generate ImapMessage from Response Object


I've created a custom command to retrieve multiple objects in the same request (in order to solve some performance issues), instead of using the folder method .getMessage(..) which in my case retrieved an ImapMessage object:

    Argument args = new Argument();
    args.writeString(Integer.toString(start) + ":" + Integer.toString(end));
    args.writeString("BODY[]");

    FetchResponse fetch;
    BODY body;
    MimeMessage mm;
    ByteArrayInputStream is = null;
    Response[] r = protocol.command("FETCH", args);
    Response status = r[r.length-1];
    if(status.isOK()) {
        for (int i = 0; i < r.length - 1; i++) {
            ...
        }
    }

Currently I'm validating if the object is a ImapResponse like this:

    if (r[i] instanceof IMAPResponse) {
       IMAPResponse imr = (IMAPResponse)r[i];

My question is, how can I turn this response into an ImapMessage?

Thank you.


Solution

  • I haven't succeeded yet to convert it into a IMAPMessage but I'm now able transform it into a MIME Message. It isn't perfect but I guess it will have to work for now:

    FetchResponse fetch = (FetchResponse) r[i];
    BODY body = (BODY) fetch.getItem(0);
    ByteArrayInputStream is = body.getByteArrayInputStream();
    MimeMessage mm = new MimeMessage(session, is);
    

    Then, it can be used to get information like this:

    String contentType = mm.getContentType();
    Object contentObject = mm.getContent();
    

    There are also other methods to get information like the sender, date, etc.