{"id":20929497,"url":"https://github.com/integration-automation/mailthunder","last_synced_at":"2026-05-21T04:36:53.551Z","repository":{"id":41415727,"uuid":"348348137","full_name":"Integration-Automation/MailThunder","owner":"Integration-Automation","description":null,"archived":false,"fork":false,"pushed_at":"2026-04-25T09:07:28.000Z","size":257,"stargazers_count":4,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2026-04-25T09:28:46.714Z","etag":null,"topics":["imap-client","python","smtp-client"],"latest_commit_sha":null,"homepage":"https://integration-automation.github.io/MailThunder/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Integration-Automation.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2021-03-16T12:57:43.000Z","updated_at":"2026-04-25T09:07:32.000Z","dependencies_parsed_at":"2025-03-13T01:42:10.649Z","dependency_job_id":"47951b8a-6a6a-4acc-91ff-756eaf2eaa98","html_url":"https://github.com/Integration-Automation/MailThunder","commit_stats":null,"previous_names":["intergration-automation-testing/mailthunder","integration-automation/mailthunder"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Integration-Automation/MailThunder","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Integration-Automation%2FMailThunder","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Integration-Automation%2FMailThunder/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Integration-Automation%2FMailThunder/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Integration-Automation%2FMailThunder/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Integration-Automation","download_url":"https://codeload.github.com/Integration-Automation/MailThunder/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Integration-Automation%2FMailThunder/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33288911,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-21T02:57:32.698Z","status":"ssl_error","status_checked_at":"2026-05-21T02:57:31.990Z","response_time":62,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["imap-client","python","smtp-client"],"created_at":"2024-11-18T21:20:17.730Z","updated_at":"2026-05-21T04:36:53.545Z","avatar_url":"https://github.com/Integration-Automation.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# MailThunder\n\n[![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)\n[![Python](https://img.shields.io/badge/python-3.9%2B-blue.svg)](https://www.python.org/)\n[![PyPI](https://img.shields.io/pypi/v/je_mail_thunder)](https://pypi.org/project/je-mail-thunder/)\n\n**MailThunder** is a lightweight and flexible email automation tool for Python. It wraps SMTP and IMAP4 protocols, provides a JSON-based scripting engine and project templates, and makes sending, receiving, and managing email content effortless.\n\n**[繁體中文](README/README_zh-TW.md)** | **[简体中文](README/README_zh-CN.md)**\n\n---\n\n## Table of Contents\n\n- [Features](#features)\n- [Requirements](#requirements)\n- [Installation](#installation)\n- [Quick Start](#quick-start)\n  - [Configuration](#configuration)\n  - [Sending an Email (SMTP)](#sending-an-email-smtp)\n  - [Sending an Email with Attachment](#sending-an-email-with-attachment)\n  - [Reading Emails (IMAP)](#reading-emails-imap)\n  - [Exporting All Emails to Files](#exporting-all-emails-to-files)\n- [Authentication](#authentication)\n  - [JSON Config File](#json-config-file)\n  - [Environment Variables](#environment-variables)\n- [Scripting Engine](#scripting-engine)\n  - [Action JSON Format](#action-json-format)\n  - [Available Script Commands](#available-script-commands)\n  - [Extending with Custom Commands](#extending-with-custom-commands)\n  - [Dynamic Package Loading](#dynamic-package-loading)\n- [Project Templates](#project-templates)\n- [Command-Line Interface](#command-line-interface)\n- [Socket Server](#socket-server)\n- [API Reference](#api-reference)\n  - [SMTPWrapper](#smtpwrapper)\n  - [IMAPWrapper](#imapwrapper)\n  - [Executor Functions](#executor-functions)\n  - [Utility Functions](#utility-functions)\n- [Project Structure](#project-structure)\n- [License](#license)\n\n---\n\n## Features\n\n- **SMTP support** — Send emails via SSL with Gmail (default) or any SMTP provider\n- **IMAP4 support** — Read, search, and export emails via IMAP4 SSL\n- **Attachment handling** — Automatically detect MIME types for text, image, audio, and binary files\n- **HTML email** — Send HTML-formatted emails with attachments\n- **JSON scripting engine** — Automate email workflows using JSON action files\n- **Project templates** — Scaffold projects with pre-built keyword and executor templates\n- **Socket server** — Control MailThunder remotely via TCP socket commands\n- **Package manager** — Dynamically load Python packages into the scripting executor\n- **Environment variable auth** — Authenticate via config file or OS environment variables\n- **Auto-export** — Export all mailbox emails to local files in one call\n- **Context manager support** — Use `with` statement for both SMTP and IMAP connections\n- **Logging** — Built-in logging for all operations\n\n---\n\n## Requirements\n\n- Python 3.9 or later\n\n---\n\n## Installation\n\n**Stable release:**\n\n```bash\npip install je_mail_thunder\n```\n\n**Development release:**\n\n```bash\npip install je_mail_thunder_dev\n```\n\n---\n\n## Quick Start\n\n### Configuration\n\nBefore using MailThunder, you need to set up authentication. Create a file named `mail_thunder_content.json` in your current working directory:\n\n```json\n{\n  \"user\": \"your_email@gmail.com\",\n  \"password\": \"your_app_password\"\n}\n```\n\n\u003e **Important:** If you are using Gmail, you must use an [App Password](https://support.google.com/accounts/answer/185833), not your regular Google account password. You also need to [enable IMAP](https://support.google.com/mail/answer/7126229?hl=en) in your Gmail settings.\n\n### Sending an Email (SMTP)\n\n```python\nfrom je_mail_thunder import SMTPWrapper\n\nwith SMTPWrapper() as smtp:\n    smtp.later_init()  # Log in using config file or env vars\n    smtp.create_message_and_send(\n        message_content=\"Hello from MailThunder!\",\n        message_setting_dict={\n            \"Subject\": \"Test Email\",\n            \"From\": \"sender@gmail.com\",\n            \"To\": \"receiver@gmail.com\"\n        }\n    )\n```\n\n### Sending an Email with Attachment\n\n```python\nfrom je_mail_thunder import SMTPWrapper\n\nwith SMTPWrapper() as smtp:\n    smtp.later_init()\n    smtp.create_message_with_attach_and_send(\n        message_content=\"Please see the attached file.\",\n        message_setting_dict={\n            \"Subject\": \"Email with Attachment\",\n            \"From\": \"sender@gmail.com\",\n            \"To\": \"receiver@gmail.com\"\n        },\n        attach_file=\"/path/to/file.pdf\",\n        use_html=False  # Set True if message_content is HTML\n    )\n```\n\n### Reading Emails (IMAP)\n\n```python\nfrom je_mail_thunder import IMAPWrapper\n\nwith IMAPWrapper() as imap:\n    imap.later_init()  # Log in\n    imap.select_mailbox(\"INBOX\")\n    emails = imap.mail_content_list()\n    for mail in emails:\n        print(f\"Subject: {mail['SUBJECT']}\")\n        print(f\"From: {mail['FROM']}\")\n        print(f\"Body: {mail['BODY'][:100]}...\")\n```\n\n### Exporting All Emails to Files\n\n```python\nfrom je_mail_thunder import IMAPWrapper\n\nwith IMAPWrapper() as imap:\n    imap.later_init()\n    imap.select_mailbox(\"INBOX\")\n    imap.output_all_mail_as_file()  # Saves each email as a file named by subject\n```\n\n---\n\n## Authentication\n\nMailThunder supports two authentication methods. It tries the JSON config file first, then falls back to environment variables.\n\n### JSON Config File\n\nPlace `mail_thunder_content.json` in the current working directory:\n\n```json\n{\n  \"user\": \"your_email@gmail.com\",\n  \"password\": \"your_app_password\"\n}\n```\n\n### Environment Variables\n\nSet these environment variables before running your script:\n\n```python\nfrom je_mail_thunder import set_mail_thunder_os_environ\n\nset_mail_thunder_os_environ(\n    mail_thunder_user=\"your_email@gmail.com\",\n    mail_thunder_user_password=\"your_app_password\"\n)\n```\n\nOr set them in your shell:\n\n```bash\nexport mail_thunder_user=\"your_email@gmail.com\"\nexport mail_thunder_user_password=\"your_app_password\"\n```\n\n---\n\n## Scripting Engine\n\nMailThunder includes a JSON-based scripting engine that lets you automate email workflows without writing Python code.\n\n### Action JSON Format\n\nAction files use a list of commands. Each command is an array where the first element is the command name and the optional second element contains the arguments:\n\n```json\n{\n  \"auto_control\": [\n    [\"command_name\"],\n    [\"command_name\", {\"key\": \"value\"}],\n    [\"command_name\", [\"arg1\", \"arg2\"]]\n  ]\n}\n```\n\n- Use a **dict** `{}` as the second element for keyword arguments (`**kwargs`)\n- Use a **list** `[]` as the second element for positional arguments (`*args`)\n- Use only the command name (no second element) for commands with no arguments\n\n### Available Script Commands\n\n| Command | Description | Arguments |\n|---------|-------------|-----------|\n| `MT_smtp_later_init` | Initialize and log in to SMTP | None |\n| `MT_smtp_create_message_and_send` | Create and send an email | `{\"message_content\": str, \"message_setting_dict\": dict}` |\n| `MT_smtp_create_message_with_attach_and_send` | Create and send an email with attachment | `{\"message_content\": str, \"message_setting_dict\": dict, \"attach_file\": str, \"use_html\": bool}` |\n| `smtp_quit` | Disconnect from SMTP server | None |\n| `MT_imap_later_init` | Initialize and log in to IMAP | None |\n| `MT_imap_select_mailbox` | Select a mailbox | `{\"mailbox\": str, \"readonly\": bool}` (default: INBOX) |\n| `MT_imap_search_mailbox` | Search and get mail details | `{\"search_str\": str, \"charset\": str}` |\n| `MT_imap_mail_content_list` | Get all mail content as list | `{\"search_str\": str, \"charset\": str}` |\n| `MT_imap_output_all_mail_as_file` | Export all emails to files | `{\"search_str\": str, \"charset\": str}` |\n| `MT_imap_quit` | Disconnect from IMAP server | None |\n| `MT_set_mail_thunder_os_environ` | Set auth env vars | `{\"mail_thunder_user\": str, \"mail_thunder_user_password\": str}` |\n| `MT_get_mail_thunder_os_environ` | Get auth env vars | None |\n| `MT_add_package_to_executor` | Load a Python package into executor | `[\"package_name\"]` |\n\n**Example — Send an email via JSON script:**\n\n```json\n{\n  \"auto_control\": [\n    [\"MT_smtp_later_init\"],\n    [\"MT_smtp_create_message_and_send\", {\n      \"message_content\": \"Hello World!\",\n      \"message_setting_dict\": {\n        \"Subject\": \"Automated Email\",\n        \"To\": \"receiver@gmail.com\",\n        \"From\": \"sender@gmail.com\"\n      }\n    }],\n    [\"smtp_quit\"]\n  ]\n}\n```\n\n**Example — Read and export all emails:**\n\n```json\n{\n  \"auto_control\": [\n    [\"MT_imap_later_init\"],\n    [\"MT_imap_select_mailbox\"],\n    [\"MT_imap_output_all_mail_as_file\"]\n  ]\n}\n```\n\n### Extending with Custom Commands\n\nYou can add your own functions to the scripting executor:\n\n```python\nfrom je_mail_thunder import add_command_to_executor\n\ndef my_custom_function(param1, param2):\n    print(f\"Custom: {param1}, {param2}\")\n\nadd_command_to_executor({\"my_command\": my_custom_function})\n```\n\nThen use `\"my_command\"` in your JSON action files.\n\n### Dynamic Package Loading\n\nLoad any installed Python package into the executor at runtime:\n\n```json\n{\n  \"auto_control\": [\n    [\"MT_add_package_to_executor\", [\"os\"]],\n    [\"os_system\", [\"echo Hello from os.system\"]]\n  ]\n}\n```\n\nThis loads all functions, builtins, and classes from the specified package, prefixed with `packagename_`.\n\n\u003e **Warning:** Loading packages like `os` into the executor can be a security risk. Only load trusted packages and validate all inputs.\n\n---\n\n## Project Templates\n\nMailThunder can scaffold a project with pre-built templates:\n\n```python\nfrom je_mail_thunder import create_project_dir\n\ncreate_project_dir()  # Creates in current directory\n# or\ncreate_project_dir(project_path=\"/path/to/project\", parent_name=\"MyMailProject\")\n```\n\nThis creates the following structure:\n\n```\nMyMailProject/\n  keyword/\n    keyword1.json      # SMTP send email template\n    keyword2.json      # IMAP read and export template\n    bad_keyword_1.json # Package loading example (security warning)\n  executor/\n    executor_one_file.py   # Execute a single action file\n    executor_folder.py     # Execute all action files in a directory\n    executor_bad_file.py   # Bad practice example\n```\n\n---\n\n## Command-Line Interface\n\nMailThunder provides a CLI via `python -m je_mail_thunder`:\n\n```bash\n# Execute a single JSON action file\npython -m je_mail_thunder -e /path/to/action.json\n\n# Execute all JSON action files in a directory\npython -m je_mail_thunder -d /path/to/actions/\n\n# Execute a JSON string directly\npython -m je_mail_thunder --execute_str '[[\"MT_smtp_later_init\"], [\"smtp_quit\"]]'\n\n# Create a new project with templates\npython -m je_mail_thunder -c /path/to/project\n```\n\n| Flag | Long Flag | Description |\n|------|-----------|-------------|\n| `-e` | `--execute_file` | Execute a single JSON action file |\n| `-d` | `--execute_dir` | Execute all JSON action files in a directory |\n| `-c` | `--create_project` | Create a project with templates |\n| | `--execute_str` | Execute a JSON string directly |\n\n---\n\n## Socket Server\n\nMailThunder includes a TCP socket server that accepts JSON commands remotely:\n\n```python\nfrom je_mail_thunder.utils.socket_server.mail_thunder_socket_server import start_autocontrol_socket_server\n\nserver = start_autocontrol_socket_server(host=\"localhost\", port=9944)\n# Server is now running in a background thread\n```\n\n**Sending commands to the server:**\n\n```python\nimport socket\nimport json\n\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nclient.connect((\"localhost\", 9944))\n\n# Send an action command\ncommand = json.dumps([[\"MT_smtp_later_init\"], [\"smtp_quit\"]])\nclient.send(command.encode(\"utf-8\"))\n\n# Receive response\nresponse = client.recv(8192).decode(\"utf-8\")\nprint(response)\n\nclient.close()\n```\n\nSend `\"quit_server\"` to shut down the server.\n\n---\n\n## API Reference\n\n### SMTPWrapper\n\nExtends `smtplib.SMTP_SSL`. Default host: `smtp.gmail.com`, default port: `465`.\n\n| Method | Description |\n|--------|-------------|\n| `later_init()` | Log in using config file or environment variables |\n| `create_message(message_content, message_setting_dict, **kwargs)` | Create an `EmailMessage` object |\n| `create_message_with_attach(message_content, message_setting_dict, attach_file, use_html=False)` | Create a `MIMEMultipart` message with attachment |\n| `create_message_and_send(message_content, message_setting_dict, **kwargs)` | Create and immediately send an email |\n| `create_message_with_attach_and_send(message_content, message_setting_dict, attach_file, use_html=False)` | Create and send an email with attachment |\n| `try_to_login_with_env_or_content()` | Attempt login from config or env vars, returns `bool` |\n| `quit()` | Disconnect and close |\n\n**Using a different SMTP provider:**\n\n```python\nfrom je_mail_thunder import SMTPWrapper\n\n# Example: Outlook\nsmtp = SMTPWrapper(host=\"smtp.office365.com\", port=587)\n```\n\n### IMAPWrapper\n\nExtends `imaplib.IMAP4_SSL`. Default host: `imap.gmail.com`.\n\n| Method | Description |\n|--------|-------------|\n| `later_init()` | Log in using config file or environment variables |\n| `select_mailbox(mailbox=\"INBOX\", readonly=False)` | Select a mailbox, returns `bool` |\n| `search_mailbox(search_str=\"ALL\", charset=None)` | Search and return raw mail details as list |\n| `mail_content_list(search_str=\"ALL\", charset=None)` | Return parsed mail content as list of dicts |\n| `output_all_mail_as_file(search_str=\"ALL\", charset=None)` | Export all emails to files named by subject |\n| `quit()` | Close mailbox and logout |\n\n**Mail content dict format:**\n\n```python\n{\n    \"SUBJECT\": \"Email subject\",\n    \"FROM\": \"sender@example.com\",\n    \"TO\": \"receiver@example.com\",\n    \"BODY\": \"Email body content...\"\n}\n```\n\n### Executor Functions\n\n| Function | Description |\n|----------|-------------|\n| `execute_action(action_list)` | Execute a list of action commands |\n| `execute_files(execute_files_list)` | Execute multiple JSON action files |\n| `add_command_to_executor(command_dict)` | Add custom functions to the executor |\n| `read_action_json(file_path)` | Read a JSON action file |\n\n### Utility Functions\n\n| Function | Description |\n|----------|-------------|\n| `create_project_dir(project_path, parent_name)` | Create a project with templates |\n| `set_mail_thunder_os_environ(user, password)` | Set authentication environment variables |\n| `get_mail_thunder_os_environ()` | Get authentication environment variables |\n| `read_output_content()` | Read `mail_thunder_content.json` from cwd |\n| `write_output_content()` | Write content data to `mail_thunder_content.json` |\n| `get_dir_files_as_list(path)` | Get all files in a directory as list |\n\n---\n\n## Project Structure\n\n```\nMailThunder/\n  je_mail_thunder/\n    __init__.py              # Public API exports\n    __main__.py              # CLI entry point\n    smtp/\n      smtp_wrapper.py        # SMTPWrapper class\n    imap/\n      imap_wrapper.py        # IMAPWrapper class\n    utils/\n      exception/             # Custom exceptions and error tags\n      executor/              # JSON scripting engine\n      file_process/          # File utility functions\n      json/                  # JSON file read/write\n      json_format/           # JSON formatting\n      logging/               # Logger instance\n      package_manager/       # Dynamic package loader\n      project/               # Project template scaffolding\n      save_mail_user_content/ # Auth config and env var handling\n      socket_server/         # TCP socket server\n  test/                      # Unit tests\n  docs/                      # Sphinx documentation\n```\n\n---\n\n## License\n\nThis project is licensed under the [MIT License](LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fintegration-automation%2Fmailthunder","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fintegration-automation%2Fmailthunder","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fintegration-automation%2Fmailthunder/lists"}