commit db2537d3a51f827855337e25e9c2ea321d6d9572 Author: Antonio J. Delgado Date: Fri Apr 7 22:39:52 2023 +0300 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..297e1f5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,142 @@ + Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# Configuration files +*.conf +*.ini diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e69de29 diff --git a/README.md b/README.md new file mode 100644 index 0000000..77ae1d3 --- /dev/null +++ b/README.md @@ -0,0 +1,23 @@ +# list_imap_messages + +## Requirements + +## Installation + +### Linux + + ```bash +sudo python3 setup.py install +``` + +### Windows (from PowerShell) + + ```powershell +& $(where.exe python).split()[0] setup.py install +``` + +## Usage + + ```bash +list_imap_messages.py [--debug-level|-d CRITICAL|ERROR|WARNING|INFO|DEBUG|NOTSET] # Other parameters +``` diff --git a/list_imap_messages/__init__.py b/list_imap_messages/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/list_imap_messages/list_imap_messages.py b/list_imap_messages/list_imap_messages.py new file mode 100755 index 0000000..178e312 --- /dev/null +++ b/list_imap_messages/list_imap_messages.py @@ -0,0 +1,172 @@ +#!/usr/bin/env python3 +# -*- encoding: utf-8 -*- +# +# This script is licensed under GNU GPL version 2.0 or above +# (c) 2023 Antonio J. Delgado +# List IMAP messages + +import sys +import os +import logging +import click +import click_config_file +from logging.handlers import SysLogHandler +import imaplib +import re +import json +from operator import itemgetter, attrgetter + +class Mailbox: + def __init__(self, name, count): + self.name = name + self.count = count + + def __str__(self): + return f"{self.name} {self.count}" + + def toJSON(self): + return json.dumps(self, default=lambda o: o.__dict__, + sort_keys=True, indent=4) + + def __repr__(self): + return repr((self.name, self.count)) + +class list_imap_messages: + + def __init__(self, debug_level, log_file, **kwargs): + ''' Initial function called when object is created ''' + self.config = dict() + self.config['debug_level'] = debug_level + if log_file is None: + log_file = os.path.join(os.environ.get('HOME', os.environ.get('USERPROFILE', os.getcwd())), 'log', 'list_imap_messages.log') + self.config['log_file'] = log_file + self.config.update(kwargs) + self._init_log() + if self.config['ssl']: + self._connect_ssl() + else: + self._connect() + self._login() + #self._select_mailbox() + self._list_mailboxes() + + def _list_mailboxes(self): + self._log.debug(f"Listing mailboxes in {self.config['mailbox']}") + result = self.imap.list() + if result[0] == 'NO': + self._log.error(f"Error listing mailboxes in {self.config['mailbox']}: {result[1]}") + self.imap.close() + self.imap.logout() + sys.exit(1) + else: + self._log.debug(f"Result: {result}") + mailboxes = list() + for raw_mailbox in result[1]: + self._log.debug(raw_mailbox) + mailbox_list = raw_mailbox.decode().split(' "/" ') + result = self._select_mailbox(mailbox_list[1]) + mailboxes.append( + Mailbox( + mailbox_list[1].replace('"', ''), + int(result[1][0].decode()) + ) + ) + print(json.dumps(sorted(mailboxes, key=lambda mailbox: mailbox.count, reverse=True), indent=2, default=vars)) + return result + + def _select_mailbox(self, mailbox): + try: + self._log.debug(f"Selecting mailbox '{self.config['username']}@{self.config['server']}:{self.config['port']}/{mailbox}'") + result=self.imap.select(mailbox, True) + except imaplib.IMAP4.error as error: + self._log.error(f"Error selecting mailbox '{self.config['username']}@{self.config['server']}:{self.config['port']}/{mailbox}': {error}") + self.imap.close() + self.imap.logout() + sys.exit(1) + if result[0] == 'NO': + self._log.error(f"Error selecting mailbox '{self.config['username']}@{self.config['server']}:{self.config['port']}/{mailbox}': {result[1]}") + self.imap.close() + self.imap.logout() + sys.exit(1) + else: + self._log.debug(f"Result: {result}") + return result + + def _login(self): + try: + self._log.debug(f"Login as '{self.config['username']}@{self.config['server']}:{self.config['port']}'") + self.imap.login(self.config['username'], self.config['password']) + #except imaplib.IMAP4.error as error: + except Exception as error: + self._log.error(f"Error login as '{self.config['username']}@{self.config['server']}:{self.config['port']}': {error}") + self.imap.logout() + sys.exit(1) + + def _connect_ssl(self): + try: + self._log.debug(f"Connecting to '{self.config['server']}:{self.config['port']}/SSL'") + self.imap=imaplib.IMAP4_SSL(self.config['server'], self.config['port']) + except Exception as error: + self._log.error(f"Error connecting to '{self.config['server']}:{self.config['port']}': {error}") + sys.exit(1) + + def _connect(self): + try: + self._log.debug(f"Connecting to '{self.config['server']}:{self.config['port']}/noSSL'") + self.imap=imaplib.IMAP4(self.config['server'], self.config['port']) + except Exception as error: + self._log.error(f"Error connecting to '{self.config['server']}:{self.config['port']}': {error}") + sys.exit(1) + + + def _init_log(self): + ''' Initialize log object ''' + self._log = logging.getLogger("list_imap_messages") + self._log.setLevel(logging.DEBUG) + + sysloghandler = SysLogHandler() + sysloghandler.setLevel(logging.DEBUG) + self._log.addHandler(sysloghandler) + + streamhandler = logging.StreamHandler(sys.stdout) + streamhandler.setLevel(logging.getLevelName(self.config.get("debug_level", 'INFO'))) + self._log.addHandler(streamhandler) + + if 'log_file' in self.config: + log_file = self.config['log_file'] + else: + home_folder = os.environ.get('HOME', os.environ.get('USERPROFILE', '')) + log_folder = os.path.join(home_folder, "log") + log_file = os.path.join(log_folder, "list_imap_messages.log") + + if not os.path.exists(os.path.dirname(log_file)): + os.mkdir(os.path.dirname(log_file)) + + filehandler = logging.handlers.RotatingFileHandler(log_file, maxBytes=102400000) + # create formatter + formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s') + filehandler.setFormatter(formatter) + filehandler.setLevel(logging.DEBUG) + self._log.addHandler(filehandler) + return True + +@click.command() +@click.option("--debug-level", "-d", default="INFO", + type=click.Choice( + ["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG", "NOTSET"], + case_sensitive=False, + ), help='Set the debug level for the standard output.') +@click.option('--log-file', '-l', help="File to store all debug messages.") +@click.option("--ssl","-s", is_flag=True, default=True, help="Use SSL connection usually port 993.") +@click.option("--server","-S", default='localhost', help="Server full name or IP.") +@click.option("--port","-p", default=993, help="Server port to connect.") +@click.option("--username","-u", required=True, help="User name to login.") +@click.option("--password","-w", required=True, help="User password to login.") +@click.option("--mailbox","-m", default='INBOX', help="Mailbox to start examination.") +@click_config_file.configuration_option() +def __main__(debug_level, log_file, **kwargs): + return list_imap_messages(debug_level, log_file, **kwargs) + +if __name__ == "__main__": + __main__() + diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..e72500f --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,25 @@ +[build-system] +requires = ["setuptools", "wheel"] +build-backend = "setuptools.build_meta" + +[project.urls] +Homepage = "" + +[project] +name = "list_imap_messages" +version = "0.0.1" +description = "List IMAP messages" +readme = "README.md" +authors = [{ name = "Antonio J. Delgado", email = "" }] +license = { file = "LICENSE" } +classifiers = [ + "License :: OSI Approved :: GPLv3 License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", +] +#keywords = ["vCard", "contacts", "duplicates"] +dependencies = [ + "click", + "click_config_file", +] +requires-python = ">=3" \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..66bf966 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +click +click_config_file \ No newline at end of file diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..b55d6c5 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,9 @@ +[metadata] +name = list_imap_messages +version = 0.0.1 + +[options] +packages = list_imap_messages +install_requires = + requests + importlib; python_version == "3.10" diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..b7da53f --- /dev/null +++ b/setup.py @@ -0,0 +1,14 @@ +import setuptools +setuptools.setup( + scripts=['list_imap_messages/list_imap_messages.py'], + author="Antonio J. Delgado", + version='0.0.1', + name='list_imap_messages', + author_email="", + url="", + description="List IMAP messages", + long_description="README.md", + long_description_content_type="text/markdown", + license="GPLv3", + #keywords=["my", "script", "does", "things"] +)