How to intercept incoming email and retrieve message body in thunderbird

点点圈 提交于 2020-02-22 08:45:07

问题


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.



来源:https://stackoverflow.com/questions/27265271/how-to-intercept-incoming-email-and-retrieve-message-body-in-thunderbird

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!