| 1 | #!/usr/bin/env python3 |
| 2 | """IMAP/SMTP mail client for ClonAgent IMAP-based skills. |
| 3 | |
| 4 | Reads connection settings from config.json (same dir) and the password from |
| 5 | imap-credentials.json (also same dir, mode 600). Mirrors the gmail_client.py |
| 6 | subcommands so SKILL.md flow works the same. |
| 7 | """ |
| 8 | from __future__ import annotations |
| 9 | |
| 10 | import argparse, email, imaplib, json, os, smtplib, sys |
| 11 | from email.header import decode_header |
| 12 | from email.mime.text import MIMEText |
| 13 | from email.utils import formatdate, make_msgid, parseaddr |
| 14 | from pathlib import Path |
| 15 | |
| 16 | SKILL_DIR = Path(__file__).parent |
| 17 | CONFIG_FILE = SKILL_DIR / 'config.json' |
| 18 | CREDS_FILE = SKILL_DIR / 'imap-credentials.json' |
| 19 | |
| 20 | PROCESSED_FOLDERS = ['INBOX/en-progreso-bot', 'INBOX/procesado-bot', 'INBOX/pendiente-revision-humana'] |
| 21 | |
| 22 | |
| 23 | def authorized_senders(): |
| 24 | """Devuelve [{email, role}, ...] (acepta strings legacy).""" |
| 25 | cfg = load_cfg() |
| 26 | raw = cfg.get('authorizedSenders') or [] |
| 27 | out = [] |
| 28 | for i, s in enumerate(raw): |
| 29 | if isinstance(s, str): |
| 30 | out.append({'email': s.lower(), 'role': 'owner' if i == 0 else 'reader'}) |
| 31 | elif isinstance(s, dict) and s.get('email'): |
| 32 | role = s.get('role') if s.get('role') in ('owner', 'cocreator', 'reader') else 'reader' |
| 33 | out.append({'email': s['email'].lower(), 'role': role}) |
| 34 | if not out: |
| 35 | print("❌ config.json sin authorizedSenders", file=sys.stderr); sys.exit(1) |
| 36 | return out |
| 37 | |
| 38 | |
| 39 | def authorized_emails(): |
| 40 | return [s['email'] for s in authorized_senders()] |
| 41 | |
| 42 | |
| 43 | def role_for(email: str): |
| 44 | e = (email or '').lower() |
| 45 | if '<' in e and '>' in e: |
| 46 | e = e.split('<', 1)[1].split('>', 1)[0] |
| 47 | for s in authorized_senders(): |
| 48 | if s['email'] == e: |
| 49 | return s['role'] |
| 50 | return None |
| 51 | |
| 52 | |
| 53 | def _thread_id_for(msg): |
| 54 | """Identifica el hilo de email de forma estable. |
| 55 | |
| 56 | Estrategia: el primer Message-ID en la cadena References (= el primer mensaje |
| 57 | del hilo) si existe; si no, usa el Message-ID propio. Esto coincide entre |
| 58 | todos los replies del mismo hilo. |
| 59 | """ |
| 60 | refs = (msg.get('References') or msg.get('In-Reply-To') or '').strip() |
| 61 | if refs: |
| 62 | # References puede contener varios <id> separados por whitespace |
| 63 | for token in refs.split(): |
| 64 | token = token.strip() |
| 65 | if token.startswith('<') and token.endswith('>'): |
| 66 | return token |
| 67 | own = (msg.get('Message-ID') or '').strip() |
| 68 | return own |
| 69 | |
| 70 | |
| 71 | def load_cfg() -> dict: |
| 72 | if not CONFIG_FILE.exists(): |
| 73 | sys.exit(f"missing {CONFIG_FILE}") |
| 74 | cfg = json.loads(CONFIG_FILE.read_text()) |
| 75 | if not CREDS_FILE.exists(): |
| 76 | sys.exit(f"missing {CREDS_FILE} — write {{\"password\": \"...\"}} (mode 600)") |
| 77 | cfg['password'] = json.loads(CREDS_FILE.read_text())['password'] |
| 78 | return cfg |
| 79 | |
| 80 | |
| 81 | def connect_imap(cfg): |
| 82 | cls = imaplib.IMAP4_SSL if cfg.get('imapSsl', True) else imaplib.IMAP4 |
| 83 | M = cls(cfg['imapHost'], cfg.get('imapPort', 993 if cfg.get('imapSsl', True) else 143)) |
| 84 | M.login(cfg['botEmail'], cfg['password']) |
| 85 | return M |
| 86 | |
| 87 | |
| 88 | def _decode(b): |
| 89 | if isinstance(b, bytes): |
| 90 | try: return b.decode() |
| 91 | except: return b.decode('latin-1', errors='replace') |
| 92 | return b |
| 93 | |
| 94 | |
| 95 | def _hdr(msg, name): |
| 96 | raw = msg.get(name, '') |
| 97 | parts = decode_header(raw) |
| 98 | return ''.join(_decode(p) if isinstance(p, bytes) else p for p, _ in parts) |
| 99 | |
| 100 | |
| 101 | def _ensure_folder(M, folder): |
| 102 | M.create(folder) # safe-noop if exists |
| 103 | |
| 104 | |
| 105 | def cmd_list_unread(args): |
| 106 | M = connect_imap(load_cfg()) |
| 107 | M.select('INBOX') |
| 108 | out = [] |
| 109 | for sender in authorized_senders(): |
| 110 | typ, data = M.search(None, 'UNSEEN', f'FROM "{sender["email"]}"') |
| 111 | if typ != 'OK': continue |
| 112 | for uid in data[0].split(): |
| 113 | typ, msg_data = M.fetch(uid, '(RFC822.HEADER)') |
| 114 | if typ != 'OK': continue |
| 115 | msg = email.message_from_bytes(msg_data[0][1]) |
| 116 | out.append({ |
| 117 | 'message_id': _hdr(msg, 'Message-ID'), |
| 118 | 'thread_id': _thread_id_for(msg), |
| 119 | 'uid': uid.decode(), |
| 120 | 'subject': _hdr(msg, 'Subject'), |
| 121 | 'from': _hdr(msg, 'From'), |
| 122 | 'sender_email': sender['email'], |
| 123 | 'sender_role': sender['role'], |
| 124 | 'date': _hdr(msg, 'Date'), |
| 125 | }) |
| 126 | M.logout() |
| 127 | print(json.dumps(out, ensure_ascii=False, indent=2)) |
| 128 | |
| 129 | |
| 130 | def _fetch_full(M, uid): |
| 131 | typ, msg_data = M.fetch(uid.encode(), '(RFC822)') |
| 132 | if typ != 'OK': return None |
| 133 | return email.message_from_bytes(msg_data[0][1]) |
| 134 | |
| 135 | |
| 136 | def _body(msg): |
| 137 | if msg.is_multipart(): |
| 138 | for p in msg.walk(): |
| 139 | if p.get_content_type() == 'text/plain': |
| 140 | return _decode(p.get_payload(decode=True)) |
| 141 | for p in msg.walk(): |
| 142 | if p.get_content_type() == 'text/html': |
| 143 | return _decode(p.get_payload(decode=True)) |
| 144 | return _decode(msg.get_payload(decode=True)) |
| 145 | |
| 146 | |
| 147 | def cmd_get_thread(args): |
| 148 | cfg = load_cfg() |
| 149 | M = connect_imap(cfg) |
| 150 | M.select('INBOX') |
| 151 | msg = _fetch_full(M, args.message_id) |
| 152 | if not msg: |
| 153 | sys.exit(f"message {args.message_id} not found") |
| 154 | from_ = _hdr(msg, 'From') |
| 155 | out = { |
| 156 | 'message_id': _hdr(msg, 'Message-ID'), |
| 157 | 'subject': _hdr(msg, 'Subject'), |
| 158 | 'from': from_, |
| 159 | 'sender_role': role_for(from_), |
| 160 | 'to': _hdr(msg, 'To'), |
| 161 | 'cc': _hdr(msg, 'Cc'), |
| 162 | 'date': _hdr(msg, 'Date'), |
| 163 | 'in_reply_to': _hdr(msg, 'In-Reply-To'), |
| 164 | 'references': _hdr(msg, 'References'), |
| 165 | 'body': _body(msg), |
| 166 | } |
| 167 | M.logout() |
| 168 | print(json.dumps(out, ensure_ascii=False, indent=2)) |
| 169 | |
| 170 | |
| 171 | def cmd_reply(args): |
| 172 | cfg = load_cfg() |
| 173 | M = connect_imap(cfg) |
| 174 | M.select('INBOX') |
| 175 | msg = _fetch_full(M, args.uid) |
| 176 | if not msg: |
| 177 | sys.exit(f"uid {args.uid} not found") |
| 178 | |
| 179 | from_ = parseaddr(_hdr(msg, 'From'))[1] |
| 180 | subj = _hdr(msg, 'Subject') |
| 181 | msgid = _hdr(msg, 'Message-ID') |
| 182 | refs = _hdr(msg, 'References') |
| 183 | |
| 184 | to = args.to or from_ |
| 185 | cc = args.cc.split(',') if args.cc else [e for e in authorized_emails() if e != to] |
| 186 | |
| 187 | if args.body_file: body = Path(args.body_file).read_text('utf-8') |
| 188 | elif args.body: body = args.body |
| 189 | else: body = sys.stdin.read() |
| 190 | |
| 191 | subject = args.subject or subj |
| 192 | if subject and not subject.lower().startswith('re:'): subject = f'Re: {subject}' |
| 193 | |
| 194 | reply = MIMEText(body, 'plain', 'utf-8') |
| 195 | reply['From'] = cfg['botEmail'] |
| 196 | reply['To'] = to |
| 197 | if cc: reply['Cc'] = ', '.join(cc) |
| 198 | reply['Subject'] = subject |
| 199 | reply['Date'] = formatdate(localtime=True) |
| 200 | reply['Message-ID'] = make_msgid(domain=cfg['botEmail'].split('@', 1)[1]) |
| 201 | if msgid: |
| 202 | reply['In-Reply-To'] = msgid |
| 203 | reply['References'] = f'{refs} {msgid}'.strip() if refs else msgid |
| 204 | |
| 205 | smtp_cls = smtplib.SMTP_SSL if cfg.get('smtpSsl', False) else smtplib.SMTP |
| 206 | s = smtp_cls(cfg['smtpHost'], cfg.get('smtpPort', 587)) |
| 207 | if not cfg.get('smtpSsl', False): s.starttls() |
| 208 | s.login(cfg['botEmail'], cfg['password']) |
| 209 | rcpts = [to] + cc |
| 210 | s.sendmail(cfg['botEmail'], rcpts, reply.as_string()) |
| 211 | s.quit() |
| 212 | M.logout() |
| 213 | print(json.dumps({'sent': True, 'to': to, 'cc': cc, 'subject': subject})) |
| 214 | |
| 215 | |
| 216 | def cmd_mark_read(args): |
| 217 | cfg = load_cfg() |
| 218 | M = connect_imap(cfg) |
| 219 | M.select('INBOX') |
| 220 | M.store(args.uid.encode(), '+FLAGS', '\\Seen') |
| 221 | M.logout() |
| 222 | print(json.dumps({'uid': args.uid, 'marked_read': True})) |
| 223 | |
| 224 | |
| 225 | def cmd_move(args): |
| 226 | cfg = load_cfg() |
| 227 | M = connect_imap(cfg) |
| 228 | M.select('INBOX') |
| 229 | _ensure_folder(M, args.folder) |
| 230 | M.copy(args.uid.encode(), args.folder) |
| 231 | M.store(args.uid.encode(), '+FLAGS', '\\Deleted') |
| 232 | M.expunge() |
| 233 | M.logout() |
| 234 | print(json.dumps({'uid': args.uid, 'moved_to': args.folder})) |
| 235 | |
| 236 | |
| 237 | def main(): |
| 238 | p = argparse.ArgumentParser(description='IMAP/SMTP client (ClonAgent)') |
| 239 | sub = p.add_subparsers(dest='cmd', required=True) |
| 240 | pl = sub.add_parser('list-unread'); pl.add_argument('--days', type=int, default=7) |
| 241 | pg = sub.add_parser('get-thread'); pg.add_argument('message_id') |
| 242 | pr = sub.add_parser('reply'); pr.add_argument('uid') |
| 243 | pr.add_argument('--body'); pr.add_argument('--body-file'); pr.add_argument('--subject') |
| 244 | pr.add_argument('--to'); pr.add_argument('--cc') |
| 245 | pm = sub.add_parser('mark-read'); pm.add_argument('uid') |
| 246 | pmv = sub.add_parser('move'); pmv.add_argument('uid'); pmv.add_argument('folder') |
| 247 | args = p.parse_args() |
| 248 | handlers = { |
| 249 | 'list-unread': cmd_list_unread, |
| 250 | 'get-thread': cmd_get_thread, |
| 251 | 'reply': cmd_reply, |
| 252 | 'mark-read': cmd_mark_read, |
| 253 | 'move': cmd_move, |
| 254 | } |
| 255 | handlers[args.cmd](args) |
| 256 | |
| 257 | |
| 258 | if __name__ == '__main__': |
| 259 | main() |