Skip to content

Agent Zero AI framework

feat: add process_unread_days setting to email handler

linuztx0eb6b3b4f3c1
diff --git a/plugins/_email_integration/default_config.yaml b/plugins/_email_integration/default_config.yaml
index b3879e4fe..121555b24 100644
--- a/plugins/_email_integration/default_config.yaml
+++ b/plugins/_email_integration/default_config.yaml
@@ -12,6 +12,7 @@ handlers: []
# poll_mode: seconds
# poll_interval_seconds: 15
# poll_interval_cron: "*/2 * * * *"
+# process_unread_days: 0
# sender_whitelist: []
# project: ""
# dispatcher_instructions: ""
diff --git a/plugins/_email_integration/extensions/python/job_loop/_10_email_poll.py b/plugins/_email_integration/extensions/python/job_loop/_10_email_poll.py
index 7cfbbd13f..dcfe3e7b1 100644
--- a/plugins/_email_integration/extensions/python/job_loop/_10_email_poll.py
+++ b/plugins/_email_integration/extensions/python/job_loop/_10_email_poll.py
@@ -56,6 +56,8 @@ async def _handler_poll_loop(handler_name: str) -> None:
_state_lock,
)
+ first_poll = True
+
while True:
config = plugins.get_plugin_config(PLUGIN_NAME) or {}
handlers = config.get("handlers", [])
@@ -69,6 +71,13 @@ async def _handler_poll_loop(handler_name: str) -> None:
try:
async with _state_lock:
state = _load_state()
+ # On first poll after startup, reset state so the first-run
+ # path processes recent unread emails via date-based search.
+ # Subsequent polls use normal UID tracking.
+ if first_poll:
+ if int(handler_cfg.get("process_unread_days", 0)) > 0:
+ state.pop(handler_name, None)
+ first_poll = False
await _poll_single_handler(handler_cfg, state)
_save_state(state)
except Exception as e:
diff --git a/plugins/_email_integration/helpers/handler.py b/plugins/_email_integration/helpers/handler.py
index 600a9b219..a2a9265b3 100644
--- a/plugins/_email_integration/helpers/handler.py
+++ b/plugins/_email_integration/helpers/handler.py
@@ -24,6 +24,7 @@ from plugins._email_integration.helpers.imap_client import (
connect_imap,
disconnect_imap,
fetch_new,
+ fetch_unread_since,
get_highest_uid,
connect_exchange,
fetch_unread_exchange,
@@ -78,9 +79,10 @@ async def _poll_single_handler(handler_cfg: dict, state: dict):
account_type = handler_cfg.get("account_type", "imap")
whitelist = handler_cfg.get("sender_whitelist") or []
last_uid = state.get(name, {}).get("last_uid", 0)
+ process_unread_days = int(handler_cfg.get("process_unread_days", 0))
if account_type == "exchange":
- messages = await _fetch_exchange(handler_cfg, whitelist)
+ messages = await _fetch_exchange(handler_cfg, whitelist, process_unread_days)
if messages:
await _dispatch_all(handler_cfg, messages)
return
@@ -92,11 +94,28 @@ async def _poll_single_handler(handler_cfg: dict, state: dict):
password=handler_cfg.get("password", ""),
)
try:
- # First run: record current highest UID, don't process old emails
+ # First run: optionally process unread from last N days
if last_uid == 0:
- highest = await get_highest_uid(client)
- state[name] = {"last_uid": highest}
- PrintStyle.info(f"Email ({name}): initialized, tracking from UID {highest}")
+ if process_unread_days > 0:
+ messages, highest = await fetch_unread_since(
+ client, DOWNLOAD_FOLDER, process_unread_days, whitelist or None,
+ )
+ highest = highest or await get_highest_uid(client)
+ state[name] = {"last_uid": highest}
+ if messages:
+ PrintStyle.info(
+ f"Email ({name}): processing {len(messages)} unread"
+ f" from last {process_unread_days} days"
+ )
+ await _dispatch_all(handler_cfg, messages)
+ else:
+ PrintStyle.info(
+ f"Email ({name}): no unread in last {process_unread_days} days"
+ )
+ else:
+ highest = await get_highest_uid(client)
+ state[name] = {"last_uid": highest}
+ PrintStyle.info(f"Email ({name}): initialized, tracking from UID {highest}")
return
messages, new_uid = await fetch_new(
@@ -114,13 +133,17 @@ async def _poll_single_handler(handler_cfg: dict, state: dict):
await disconnect_imap(client)
-async def _fetch_exchange(cfg: dict, whitelist: list[str]) -> list[InboundMessage]:
+async def _fetch_exchange(
+ cfg: dict, whitelist: list[str], since_days: int = 0,
+) -> list[InboundMessage]:
account = await connect_exchange(
server=cfg.get("imap_server", ""),
username=cfg.get("username", ""),
password=cfg.get("password", ""),
)
- return await fetch_unread_exchange(account, DOWNLOAD_FOLDER, whitelist or None)
+ return await fetch_unread_exchange(
+ account, DOWNLOAD_FOLDER, whitelist or None, since_days=since_days,
+ )
async def _dispatch_all(handler_cfg: dict, messages: list[InboundMessage]):
diff --git a/plugins/_email_integration/helpers/imap_client.py b/plugins/_email_integration/helpers/imap_client.py
index a57e3f6ad..0091bb2f4 100644
--- a/plugins/_email_integration/helpers/imap_client.py
+++ b/plugins/_email_integration/helpers/imap_client.py
@@ -1,4 +1,8 @@
-"""IMAP/Exchange email reader. No agent/tool dependencies."""
+"""
+IMAP/Exchange email reader.
+
+No agent/tool dependencies.
+"""
import asyncio
import email
@@ -6,6 +10,7 @@ import os
import re
import uuid
from dataclasses import dataclass, field
+from datetime import datetime, timedelta
from email.header import decode_header
from email.message import Message as EmailMessage
from fnmatch import fnmatch
@@ -133,6 +138,56 @@ async def get_highest_uid(client: IMAPClient) -> int:
return await loop.run_in_executor(None, _search)
+async def fetch_unread_since(
+ client: IMAPClient,
+ download_folder: str,
+ days: int,
+ sender_whitelist: list[str] | None = None,
+ max_messages: int = 10,
+) -> tuple[list[InboundMessage], int]:
+ """Fetch unread emails from the last N days. Returns (messages, highest_uid)."""
+ loop = asyncio.get_event_loop()
+ since_date = datetime.now() - timedelta(days=days)
+
+ def _search():
+ client.select_folder("INBOX")
+ try:
+ return client.gmail_search(
+ f"category:primary is:unread after:{since_date.strftime('%Y/%m/%d')}"
+ )
+ except Exception:
+ return client.search(["UNSEEN", "SINCE", since_date.date()]) # type: ignore[arg-type]
+
+ msg_ids = await loop.run_in_executor(None, _search)
+ if not msg_ids:
+ return [], 0
+
+ highest_uid = max(msg_ids)
+
+ if len(msg_ids) > max_messages:
+ PrintStyle.standard(
+ f"Email: {len(msg_ids)} unread, processing latest {max_messages}"
+ )
+ msg_ids = msg_ids[-max_messages:]
+ else:
+ PrintStyle.standard(
+ f"Email: found {len(msg_ids)} unread messages from last {days} days"
+ )
+
+ results: list[InboundMessage] = []
+ for msg_id in msg_ids:
+ try:
+ msg = await _fetch_single(client, msg_id, download_folder, sender_whitelist)
+ if msg:
+ results.append(msg)
+ except Exception as e:
+ PrintStyle.error(
+ f"Email: error processing message {msg_id}: {format_error(e)}"
+ )
+
+ return results, highest_uid
+
+
async def _fetch_single(
client: IMAPClient,
msg_id: int,
@@ -208,13 +263,18 @@ async def fetch_unread_exchange(
account,
download_folder: str,
sender_whitelist: list[str] | None = None,
+ since_days: int = 0,
) -> list[InboundMessage]:
from exchangelib import Q
loop = asyncio.get_event_loop()
def _sync():
- return list(account.inbox.filter(Q(is_read=False)))
+ q = Q(is_read=False)
+ if since_days > 0:
+ since = datetime.now(tz=account.default_timezone) - timedelta(days=since_days)
+ q &= Q(datetime_received__gte=since)
+ return list(account.inbox.filter(q))
items = await loop.run_in_executor(None, _sync)
results: list[InboundMessage] = []
diff --git a/plugins/_email_integration/webui/config.html b/plugins/_email_integration/webui/config.html
index d353ff4ae..bd22536dc 100644
--- a/plugins/_email_integration/webui/config.html
+++ b/plugins/_email_integration/webui/config.html
@@ -24,6 +24,7 @@
poll_mode: 'seconds',
poll_interval_seconds: 15,
poll_interval_cron: '*/2 * * * *',
+ process_unread_days: 0,
sender_whitelist: [],
project: '',
dispatcher_instructions: '',
@@ -194,6 +195,16 @@
</div>
</div>
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">Process Unread (days)</div>
+ <div class="field-description">On first run, process unread emails from the last N days. 0 = skip existing emails.</div>
+ </div>
+ <div class="field-control">
+ <input type="number" x-model.number="handler.process_unread_days" min="0" placeholder="0" />
+ </div>
+ </div>
+
<div class="field">
<div class="field-label">
<div class="field-title">Sender Whitelist</div>