def _findChandlerMessages(self, msgUIDs, start, total): if __debug__: trace("_findChandlerMessages") for msgUID in msgUIDs: # Add all messages that match the # search criteria to the foundUIDs # list. self.vars.foundUIDs.append(msgUID) mset = self._getSearchMessageSet() if mset: query = imap4.Query(header=('X-Chandler-Mailer', 'True'), undeleted=True, uid=mset) end = start + len(mset) d = self.proto.search(query, uid=1) d.addCallback(self._findChandlerMessages, end, total) d.addErrback(self.catchErrors) self._printSearchNum(start, end, total) return None # This point is reached when self._getSearchMessageSet() # returns None indicating that there are no more message # uids to search for Chandler Headers. if len(self.vars.foundUIDs) == 0: # If the search returned no message uids # then have the worker commit the last seen UID # for the folder to prevent searching the same # messages again. return self._getNextFolder() # Search found one or more messages containing the # Chandler Headers. msgSet = imap4.MessageSet() for uid in self.vars.foundUIDs: msgSet.add(uid) # FYI: Since there are messages to download the incrementing of # the lastUID to highest uid of the searched messages # will automatically get commited. d = self.proto.fetchFlags(msgSet, uid=True) # The True argument indicates the message UIDs were # retrieved from an IMAP Search. This flag # tells the _getMessageFlagsUID method to # perform logic specific to the results of a # search d.addCallback(self._getMessagesFlagsUID, True) d.addErrback(self.catchErrors) return None
def imap_pooling(self): # Todo: errors in defer logger.debug("fetching mails") client = yield self.imap_endpoint.connect(self.imap_factory) imap_user = self.getProp(self.__class__.PROP_USER) imap_pass = self.getProp(self.__class__.PROP_PASS) yield client.login(imap_user, imap_pass) inbox = yield client.select('INBOX') ids = yield client.search( imap4.Query( unseen=True ), uid=True ) phone = self.getProp(self.__class__.PROP_DST_PHONE) if '@' in phone: to = phone elif '-' in phone: to = "*****@*****.**" % phone else: to = "*****@*****.**" % phone for id in ids: msgs = yield client.fetchMessage( id, uid=True ) for k in msgs: #print "----------> POOL ", msgs[k]['RFC822'] self.send_yowsup(to, msgs[k]['RFC822']) # todo: must mask as readed on yowsup ack, need a queue for that!!! yield client.addFlags( id, "Seen", uid=True) yield client.logout()
def cbExamineMbox(result, proto): """ Callback invoked when examine command completes. Search for recent messages. """ return proto.search(imap4.Query(sorted=1, recent=1)).addCallback(cbRecent, proto)
def findMail(self, **kw): """Search for a mail """ if not self.connected: raise Exception("Not connected") query = imap4.Query(**kw) mails = yield self.proto.search(query.encode()) defer.returnValue(mails)
def _poll_qualified_mails(target_mailbox_info, pipeline): def handle_error(failure): logger.error('IMAP4 search failed because of {}'.format(failure)) if target_mailbox_info is not None: summary = parse_mailbox_info(target_mailbox_info) logger.info(' Read-only: {}, Total: {}, Has Unseen: {}'.format( summary.read_only, summary.total_count, summary.has_unseen)) return pipeline.protocol.search(imap4.Query(unseen=True), uid=True) \ .addCallback(_fetch_qualified_mails, pipeline) \ .addErrback(handle_error)
def loggedin(res, proto): list = yield proto.list('','*') yield mailboxes(list) yield proto.examine("[Gmail]/Chats") query = imap4.Query(all=True, uid='4900:*') print query ret = yield proto.search(query) print ret for msgid in ret: ret = yield proto.fetchFull(msgid) print ret ret = yield proto.fetchBody(msgid) print ret
def cb_mbox_select(self, mbox_info): """ Callback invoked when select command completes. Search for unseen messages. :param mbox_info (dict): Mailbox information. See twisted.mail.imap4.IMAP4Client.html#select for details. :return: deferred whose callback will be invoked with a list of all the message sequence numbers return by the search, or whose errback will be invoked if there is an error. """ new = imap4.Query(unseen=True, sorted=True) log.debug( "IMAP:: Examining mailbox {}. " "Trying to fetch unseen messages.".format(self.mbox) ) return self.proto.search( new ).addCallback(self.cb_fetchmail).addErrback(self.eb_fetchmail)
def cbInboxSelected(self, result): self.log.debug("IMAP Inbox selected") self.search(imap4.Query(unseen=True)).addCallback(self.cbGotSearch)
def _doSearchUnseen(self, result, callback): #@UnusedVariable # pylint: disable-msg=W0613 # debug('[EmailAccount] %s: _doSearchUnseen' %(self._name)) self._proto.search(imap4.Query(unseen=1)).addCallback(callback).addErrback(self._ebNotify, '_doSearchUnseen', _("cannot get list of new messages"))
def _searchForChandlerMessages(self, msgs): if __debug__: trace("_searchForChandlerHeaders") for uidDict in msgs.values(): uid = int(uidDict['UID']) if uid >= self.vars.lastUID: # Microsoft Exchange Server returnes UID's # less than the value in self.vars.lastUID. # This violates RFC 3501 and results in # Chandler messages being re-downloaded on # each sync. # # Exchange Example: # >>> C: 0004 UID FETCH 3:* (UID) # >>> S: * 2 FETCH (UID 2) self.vars.searchUIDs.append(uid) # Sort the uids since the ordering returned from the # dict may not be sequential self.vars.searchUIDs.sort() size = len(self.vars.searchUIDs) if size == 0: # There are no uids greater than the lastUID so # scan the next folder return self._getNextFolder() # The last position in the sorted searchUIDs list # is the highest uid in the folder. # This value will get commited after # all processing is done on the folder. self.vars.lastSearchUID = self.vars.searchUIDs[size - 1] # mset will never be None here since the check to # make sure the self.vars.searchUIDs list is not # empty has already been done a few lines up. mset = self._getSearchMessageSet() # Find all mail in the folder that contains the header # X-Chandler-Mailer: True, does not contain the \Deleted # flag and is greater than the IMAP UID of the last # message downloaded from the folder. query = imap4.Query(header=('X-Chandler-Mailer', 'True'), undeleted=True, uid=mset) start = 0 end = len(mset) total = size d = self.proto.search(query, uid=1) d.addCallback(self._findChandlerMessages, end, total) d.addErrback(self.catchErrors) self._printSearchNum(start, end, total) return None
def get_unseen_messages(conn, callback): return conn.search(imap4.Query(unseen=True), uid=True).addCallback(list_messages, conn, callback)