How to intercept incoming email and retrieve messa

2019-05-19 07:57发布

问题:

In my Thunderbird add-on I want to listen to new incoming emails and process the message body.

So I have written a mailListener and added it to an instance of nsIMsgFolderNotificationService.

The listener works fine and notifies when a mail comes. I get the nsIMsgDBHdr object which was fetched, but I cannot stream the message for the particular folder in the msgAdded function of my mailListener. it hangs, and I cannot even see the message body in the Thunderbird's message pane.

I think the nsISyncStreamListener used to stream the message from the folder waits for OnDataAvailable event which is not yet triggered inside the mailListener's msgAdded function.

Any inputs on how to fetch message body when a new email comes? Below is the code for my mailListener

var newMailListener = {
        msgAdded: function(aMsgHdr) {
           if( !aMsgHdr.isRead ){
                let folder = aMsgHdr.folder;
                if(aMsgHdr.recipients == "myemail+special@gmail.com"){
                    let messenger = Components.classes["@mozilla.org/messenger;1"]
                    .createInstance(Components.interfaces.nsIMessenger);
                    let listener = Components.classes["@mozilla.org/network/sync-stream-listener;1"]
                        .createInstance(Components.interfaces.nsISyncStreamListener);
                    let uri = aMsgHdr.folder.getUriForMsg(aMsgHdr);
                    messenger.messageServiceFromURI(uri).streamMessage(uri, listener, null, null, false, "");
                    let messageBody = aMsgHdr.folder.getMsgTextFromStream(listener.inputStream,
                           aMsgHdr.Charset,
                           65536,
                           32768,
                           false,
                           true,
                           { });
                    alert("the message body : " + messageBody);

                }
            }
        }
    };

回答1:

I had a similar problem. The solution I found (not easily) is to use MsgHdrToMimeMessage from mimemsg.js as Gloda is not available yet. This uses the callback function:

var newMailListener = {
  msgAdded: function(aMsgHdr) {
    if( !aMsgHdr.isRead ){
      MsgHdrToMimeMessage(aMsgHdr, null, function (aMsgHdr, aMimeMessage) {
       // do something with aMimeMessage:
       alert("the message body : " + aMimeMessage.coerceBodyToPlaintext());

       //alert(aMimeMessage.allUserAttachments.length);
       //alert(aMimeMessage.size);
      }, true);
    }
  }
};

And do not forget to include the necessary module:

Components.utils.import("resource:///modules/gloda/mimemsg.js");

More folow up reading can be found e. g. here.