Example #1
0
class EmailConnector:
    def __init__(self, logger_name, host, user, password, source_mailbox,
                 dest_mailbox, error_mailbox):
        self.logger = logging.getLogger(logger_name)
        self.mailbox = MailBox(host)
        self.mailbox.login(user, password, initial_folder=source_mailbox)
        self.logger.info("Connected to " + host + " with user " + user + ".")
        self.source_mailbox = source_mailbox
        self.dest_mailbox = dest_mailbox
        self.error_mailbox = error_mailbox

    def get_messages(self):
        return list(self.mailbox.fetch())

    def move_message(self, message, error):
        if error:
            self.mailbox.move(message.uid, self.error_mailbox)
            self.logger.info("Moved email with UID " + str(message.uid) +
                             " to " + self.error_mailbox + ".")
        else:
            self.mailbox.move(message.uid, self.dest_mailbox)
            self.logger.info("Moved email with UID " + str(message.uid) +
                             " to " + self.dest_mailbox + ".")
Example #2
0
class Control():
    def __init__(self, username, password):
        print("------------------------------------------------------")
        print("-                    SIRI CONTROL                    -")
        print("-           Created by Sanjeet Chatterjee            -")
        print("-           Adapted by Pydathon                      -")
        print("-      Website: https://medium.com/@thesanjeetc      -")
        print("------------------------------------------------------")

        try:
            self.last_checked = -1
            self.mail = MailBox('imap.gmail.com')
            self.mail.login(username, password, initial_folder='Notes')

            # Gets last Note id to stop last command from executing
            uidlist = [msg.uid for msg in self.mail.fetch(AND(all=True))]
            subjects = [msg.subject for msg in self.mail.fetch(AND(all=True))]
            try:
                self.last_checked = uidlist[-1].split()[-1]
            except IndexError:
                pass
            self.load()
            self.handle()
        except imaplib.IMAP4.error:
            print("Your username and password is incorrect")
            print("Or IMAP is not enabled.")

    def load(self):
        """Try to load all modules found in the modules folder"""
        print("\n")
        print("Loading modules...")
        self.modules = []
        path = os.path.join(os.path.dirname(__file__), "modules")
        directory = pkgutil.iter_modules(path=[path])
        for finder, name, ispkg in directory:
            try:
                loader = finder.find_module(name)
                module = loader.load_module(name)
                if hasattr(module, "commandWords") \
                        and hasattr(module, "moduleName") \
                        and hasattr(module, "execute"):
                    self.modules.append(module)
                    print("The module '{0}' has been loaded, "
                          "successfully.".format(name))
                else:
                    print("[ERROR] The module '{0}' is not in the "
                          "correct format.".format(name))
            except:
                print("[ERROR] The module '" + name + "' has some errors.")
        print("\n")

    def fetch_command(self):
        """Retrieve the last Note created if new id found"""
        uidlist = [msg.uid for msg in self.mail.fetch(AND(all=True))]
        subjects = [msg.subject for msg in self.mail.fetch(AND(all=True))]
        try:
            latest_email_id = uidlist[-1].split()[-1]
        except IndexError:
            return

        if latest_email_id == self.last_checked:
            return

        self.last_checked = latest_email_id
        data = subjects[-1]
        return data.lower().strip()

    def handle(self):
        """Handle new commands
        Poll continuously every second and check for new commands.
        """
        print("Fetching commands...")
        print("\n")

        while True:
            folder_status = self.mail.folder.status('Notes')
            nb_messages = folder_status[
                "MESSAGES"]  # permet d'actualiser la mailbox
            try:
                command = self.fetch_command()
                if not command:
                    raise ControlException("No command found.")
                print("The word(s) '" +
                      unidecode.unidecode(str(command).lower()) +
                      "' have been said")
                for module in self.modules:
                    foundWords = []
                    for word in module.commandWords:
                        #print("command=",unidecode.unidecode(str(command).lower()))
                        #print("word=", unidecode.unidecode(str(word).lower()))
                        #print(unidecode.unidecode(str(word).lower()) in unidecode.unidecode(str(command).lower()))
                        if unidecode.unidecode(
                                str(word).lower()) in unidecode.unidecode(
                                    str(command).lower()):
                            foundWords.append(
                                unidecode.unidecode(str(word).lower()))
                    if len(foundWords) == len(module.commandWords):
                        try:
                            module.execute(
                                unidecode.unidecode(str(command).lower()))
                            print("The module {0} has been executed "
                                  "successfully.".format(module.moduleName))
                        except:
                            print("[ERROR] There has been an error "
                                  "when running the {0} module".format(
                                      module.moduleName))
                    else:
                        print("\n")
                    self.mail.move(self.mail.fetch(), 'notes_old')
            except (TypeError, ControlException):
                pass
            except Exception as exc:
                print("Received an exception while running: {exc}".format(
                    **locals()))
                print("Restarting...")
            time.sleep(1)
Example #3
0
# MAILBOX
# -------
# NOTE: You can use 2 approaches to perform these operations
# "by one" - Perform operation for each message separately per N commands
# "in bulk" - Perform operation for message set per 1 command

# COPY all messages from current dir to folder1, *by one
for msg in mailbox.fetch():
    res = mailbox.copy(msg.uid, 'INBOX/folder1')
# DELETE all messages from current dir to folder1, *in bulk
mailbox.delete([msg.uid for msg in mailbox.fetch()])
# FLAG unseen messages in current folder as Answered and Flagged, *in bulk
mailbox.flag([msg.uid for msg in mailbox.fetch('(UNSEEN)')], ['Answered', 'Flagged'], True)
# MOVE all messages from current dir to folder2, *in bulk
mailbox.move([msg.uid for msg in mailbox.fetch()], 'INBOX/folder2')
# mark SEEN all messages sent at 05.03.2007 in current folder as unseen, *in bulk
mailbox.seen([msg.uid for msg in mailbox.fetch("SENTON 05-Mar-2007")], False)

# FOLDERS
# -------
# LIST
for folder in mailbox.folder.list('INBOX'):
    print(folder['flags'], folder['delim'], folder['name'])
# SET
mailbox.folder.set('INBOX')
# GET
current_folder = mailbox.folder.get()
# CREATE
mailbox.folder.create('folder1')
# EXISTS
Example #4
0
class CustomMailBox():
    def __init__(self,user,pas,host='imap.gmail.com',n_per_page=40,folder='INBOX'):
        self.user=user
        self.pwd = pas
        self.host = host
        self.folder = folder
        self.n_per_page = n_per_page
    def authuser(self):
        try:
            self.Mb_main = MailBox(host=self.host)
            self.Mb_main.login(self.user,self.pwd)
            d = dict()
            for f in self.Mb_main.folder.list():
                d[f['name'].split('/')[-1]] = f['name']
            self.Mb_main.folder.set(d[self.folder])
            return d
        except:
            return False
    def getbypagenum(self,page_number,searchterm):
        d = self.authuser()
        if d:

            print(page_number,self.n_per_page,'ufifidh')
            mb = IMAPClient(self.host)
            mb.login(self.user,self.pwd)
            mb.select_folder(d[self.folder])
            if searchterm:
                ids= mb.search(['OR',['OR',[u'TEXT',f'{searchterm}'],['FROM',f'{searchterm}']],['OR',[u'SUBJECT',f'{searchterm}'],[u'BODY',f'{searchterm}']]])
            else:
                ids = mb.search()
            print(len(ids),'hmmm')
            last = math.ceil(len(ids)/self.n_per_page)
            print(last,'last page')
            page_number = last-page_number+1
            start = max(0,((page_number-1)*self.n_per_page))
            end = min(len(ids),(page_number*self.n_per_page))
            print(start,end)
            print(ids[start:end])
            return (next(self.Mb_main.fetch(AND(uid=f'{m}'),headers_only=True,reverse=True) )for m in reversed(ids[start:end])),last
    def getbyuid(self,uid):
        if self.authuser():
            return self.Mb_main.fetch(AND(uid=uid))
    def getbysearch(self,text):
        if self.authuser():
            return self.Mb_main.fetch(OR(subject=text))
    def get_searched_chunks(self):
        gen = self.get_searched_chunks()
        pass
    def get_info(self,folder='INBOX'):
        if self.authuser():
            return self.Mb_main.folder.status(folder)
    def get_folders(self):
        if self.authuser():
            return self.Mb_main.folder.list()
    def get_cur(self):
        if self.authuser():
            return self.Mb_main.folder.get()
    def create_folder(self,folder):
        if self.authuser():
            if self.Mb_main.folder.exists(folder):
               return 'no'
            self.Mb_main.folder.create(folder)
            return 'ok'
    def delete_folder(self,folder):
        if self.authuser():
            self.Mb_main.folder.delete(folder)
    def rename_folder(self,folder):
        d = self.authuser()
        if d:
            self.Mb_main.folder.rename(d[self.folder],folder)
    def delete_msg(self,uid):
        if self.authuser():
            self.Mb_main.delete(uid)
    def move_msgto(self,folder,uid):
        if self.authuser():
            self.Mb_main.move(uid,folder)
    def copy_msgto(self,folder,uid):
        if self.authuser():
            self.Mb_main.copy(uid,folder)