maco-cli 0.4.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
maco_cli/transport.py ADDED
@@ -0,0 +1,303 @@
1
+ """Authenticated IMAP and SMTP sessions over the shared mail socket layer."""
2
+ import imaplib
3
+ import logging
4
+ import os
5
+ import re
6
+ import smtplib
7
+ import ssl
8
+ import sys
9
+ from contextlib import suppress
10
+
11
+ from . import __version__
12
+ from .accounts import credential
13
+ from .errors import MacoError, MailError
14
+ from .mail_socket import MailSocket, socket_reason, tls_error
15
+
16
+
17
+ LOG = logging.getLogger(__name__)
18
+ TIMEOUT = 30
19
+ _IMAP_ERROR_CODES = re.compile(
20
+ rb"^\[(AUTHENTICATIONFAILED|AUTHORIZATIONFAILED|BADCHARSET|CANNOT|CLIENTBUG|CONTACTADMIN|"
21
+ rb"EXPIRED|INUSE|LIMIT|NONEXISTENT|NOPERM|OVERQUOTA|PRIVACYREQUIRED|SERVERBUG|UNAVAILABLE)(?=[ \]])",
22
+ re.I,
23
+ )
24
+
25
+
26
+ def _tls_context():
27
+ # Some LibreSSL builds ignore SSL_CERT_FILE when loading default roots.
28
+ return ssl.create_default_context(cafile=os.environ.get("SSL_CERT_FILE") or None)
29
+
30
+
31
+ def _connection(protocol):
32
+ try:
33
+ context = _tls_context()
34
+ except (OSError, ValueError):
35
+ raise MailError("Could not load TLS trust settings.", protocol, "tls", reason="trust_configuration") from None
36
+ return MailSocket(protocol, context)
37
+
38
+
39
+ class _IMAPClient(imaplib.IMAP4):
40
+ def __init__(self, host, port, connection):
41
+ self._mail_connection = connection
42
+ try:
43
+ super().__init__(host, port, timeout=TIMEOUT)
44
+ except BaseException:
45
+ with suppress(OSError):
46
+ if getattr(self, "sock", None) is not None:
47
+ self.sock.close()
48
+ raise
49
+
50
+ def _create_socket(self, timeout):
51
+ # imaplib's wire debug and command history can contain credentials.
52
+ self.debug = 0
53
+ sys.audit("imaplib.open", self, self.host, self.port)
54
+ return self._mail_connection.open(self.host, self.port, timeout, tls=True)
55
+
56
+ def _log(self, line):
57
+ pass
58
+
59
+ def logout(self):
60
+ try:
61
+ return super().logout()
62
+ except (OSError, imaplib.IMAP4.error):
63
+ with suppress(OSError, imaplib.IMAP4.error):
64
+ self.shutdown()
65
+ raise
66
+
67
+ def __exit__(self, *args):
68
+ # Logout on a broken socket must not replace the command failure.
69
+ with suppress(OSError, imaplib.IMAP4.error):
70
+ return super().__exit__(*args)
71
+
72
+
73
+ class _SMTPClient(smtplib.SMTP):
74
+ def __init__(self, host, port, connection, implicit_tls):
75
+ self._mail_connection = connection
76
+ self._implicit_tls = implicit_tls
77
+ self.debuglevel = 0
78
+ try:
79
+ super().__init__(host, port, timeout=TIMEOUT)
80
+ except BaseException:
81
+ with suppress(OSError):
82
+ self.close()
83
+ raise
84
+
85
+ def _get_socket(self, host, port, timeout):
86
+ return self._mail_connection.open(host, port, timeout, tls=self._implicit_tls)
87
+
88
+
89
+ def _secret(account, protocol, supplied):
90
+ if supplied is not None:
91
+ return supplied
92
+ try:
93
+ return credential(account, protocol)
94
+ except MacoError as exc:
95
+ stage = "helper_lease" if account.auth == "helper" else "credential"
96
+ exc.details = {"protocol": protocol, "stage": stage, **getattr(exc, "details", {})}
97
+ raise
98
+
99
+
100
+ def _xoauth(account, token):
101
+ return f"user={account.username}\x01auth=Bearer {token}\x01\x01"
102
+
103
+
104
+ def _imap_reason(data):
105
+ for row in data or ():
106
+ if not isinstance(row, bytes):
107
+ continue
108
+ if row.lower().startswith(b"unsafe login"):
109
+ return "Unsafe Login"
110
+ match = _IMAP_ERROR_CODES.match(row)
111
+ if match:
112
+ return match[1].upper().decode("ascii")
113
+ return None
114
+
115
+
116
+ def imap_rejection(command, status, data):
117
+ status = status if status in ("NO", "BAD", "BYE") else "INVALID_RESPONSE"
118
+ reason = _imap_reason(data)
119
+ message = f"IMAP {command} failed ({status})."
120
+ extra = {}
121
+ if reason:
122
+ message += f" The server reported {reason}."
123
+ extra["reason"] = reason
124
+ if reason == "Unsafe Login":
125
+ message += " Check the provider's third-party IMAP client settings."
126
+ return MailError(message, "imap", "imap_command", command=command, status=status, **extra)
127
+
128
+
129
+ def imap_command_error(command, exc):
130
+ if isinstance(exc, imaplib.IMAP4.readonly):
131
+ reason = "read_only"
132
+ elif isinstance(exc, imaplib.IMAP4.abort):
133
+ reason = "connection_closed"
134
+ elif isinstance(exc, OSError):
135
+ reason = socket_reason(exc)
136
+ else:
137
+ # imaplib raises on tagged BAD instead of returning it.
138
+ if exc.args and isinstance(exc.args[0], str) and re.match(r"^[A-Z]+ command error: BAD(?: |$)", exc.args[0]):
139
+ return imap_rejection(command, "BAD", ())
140
+ reason = "command_failed"
141
+ return MailError(f"IMAP {command} could not be completed.", "imap", "imap_command",
142
+ command=command, reason=reason)
143
+
144
+
145
+ def imap_command(command, operation, *args, **kwargs):
146
+ try:
147
+ status, data = operation(*args, **kwargs)
148
+ except (OSError, imaplib.IMAP4.error) as exc:
149
+ raise imap_command_error(command, exc) from None
150
+ if status != "OK":
151
+ raise imap_rejection(command, status, data)
152
+ return data
153
+
154
+
155
+ def _imap_login(conn, account, secret):
156
+ if account.protocol_auth == "password":
157
+ if "AUTH=PLAIN" in conn.capabilities:
158
+ payload = ("\0" + account.username + "\0" + secret).encode("utf-8")
159
+ conn.authenticate("PLAIN", lambda challenge: b"" if challenge else payload)
160
+ else:
161
+ # imaplib quotes the password but sends the username as given.
162
+ user = '"' + account.username.replace('\\', '\\\\').replace('"', '\\"') + '"'
163
+ conn.login(user, secret)
164
+ else:
165
+ payload = _xoauth(account, secret).encode("utf-8")
166
+ conn.authenticate("XOAUTH2", lambda challenge: b"" if challenge else payload)
167
+
168
+
169
+ def _identify_imap(conn):
170
+ # Servers can expose a different extension set after authentication.
171
+ _, data = conn.response("CAPABILITY")
172
+ if not data or data[-1] is None:
173
+ data = imap_command("CAPABILITY", conn.capability)
174
+ try:
175
+ conn.capabilities = tuple(data[-1].decode("ascii").upper().split())
176
+ if not conn.capabilities:
177
+ raise ValueError()
178
+ except (IndexError, AttributeError, UnicodeError, ValueError):
179
+ raise MailError("The IMAP server returned invalid capabilities.", "imap", "imap_command",
180
+ command="CAPABILITY", reason="invalid_response") from None
181
+ if "ID" in conn.capabilities:
182
+ try:
183
+ # NetEase requires client identification after login, before opening a mailbox.
184
+ status, _ = conn.xatom("ID", f'("name" "Maco CLI" "version" "{__version__}")')
185
+ LOG.debug("protocol=imap command=ID outcome=%s", "accepted" if status == "OK" else "rejected")
186
+ except (imaplib.IMAP4.abort, OSError) as exc:
187
+ raise imap_command_error("ID", exc) from None
188
+ except imaplib.IMAP4.error:
189
+ # A server that rejects this optional command can still serve mail.
190
+ LOG.debug("protocol=imap command=ID outcome=rejected")
191
+
192
+
193
+ def connect_imap(account, *, secret=None):
194
+ secret = _secret(account, "imap", secret)
195
+ connection = _connection("imap")
196
+ try:
197
+ conn = _IMAPClient(account.imap_host, account.imap_port, connection)
198
+ except (imaplib.IMAP4.error, OSError) as exc:
199
+ raise imap_command_error("GREETING/CAPABILITY", exc) from None
200
+ try:
201
+ try:
202
+ _imap_login(conn, account, secret)
203
+ except (imaplib.IMAP4.abort, OSError):
204
+ raise MailError("The IMAP connection was interrupted during authentication.", "imap", "mailbox_auth",
205
+ reason="connection_interrupted") from None
206
+ except UnicodeError:
207
+ raise MailError("The IMAP authentication method cannot encode the configured credential.",
208
+ "imap", "mailbox_auth", reason="invalid_credential_encoding") from None
209
+ except imaplib.IMAP4.error as exc:
210
+ raise MailError("IMAP authentication failed. Check the mailbox credential and IMAP access.",
211
+ "imap", "mailbox_auth", reason=_imap_reason(exc.args) or "rejected") from None
212
+ LOG.debug("protocol=imap stage=mailbox_auth outcome=authenticated")
213
+ _identify_imap(conn)
214
+ return conn
215
+ except BaseException:
216
+ with suppress(OSError, imaplib.IMAP4.error):
217
+ conn.shutdown()
218
+ raise
219
+
220
+
221
+ def _smtp_greeting_error(exc, command):
222
+ details = {"code": exc.smtp_code} if isinstance(exc, smtplib.SMTPResponseException) else {}
223
+ return MailError(f"SMTP {command} could not be completed.", "smtp", "smtp_command",
224
+ command=command, **details)
225
+
226
+
227
+ def _smtp_starttls(conn, context):
228
+ try:
229
+ conn.starttls(context=context)
230
+ except smtplib.SMTPHeloError as exc:
231
+ raise _smtp_greeting_error(exc, "EHLO") from None
232
+ except smtplib.SMTPNotSupportedError:
233
+ raise MailError("The SMTP server did not advertise STARTTLS.", "smtp", "tls",
234
+ command="STARTTLS", reason="starttls_unavailable") from None
235
+ except smtplib.SMTPResponseException as exc:
236
+ raise MailError("The SMTP server refused STARTTLS.", "smtp", "tls",
237
+ command="STARTTLS", reason="starttls_rejected", code=exc.smtp_code) from None
238
+ except OSError as exc:
239
+ raise tls_error("smtp", exc) from None
240
+ LOG.debug("protocol=smtp stage=tls command=STARTTLS outcome=connected")
241
+
242
+
243
+ def _smtp_login(conn, account, secret):
244
+ if account.protocol_auth == "password":
245
+ conn.login(account.username, secret)
246
+ else:
247
+ if "XOAUTH2" not in conn.esmtp_features.get("auth", "").upper().split():
248
+ raise smtplib.SMTPNotSupportedError("XOAUTH2 unavailable")
249
+ payload = _xoauth(account, secret)
250
+ conn.auth("XOAUTH2", lambda challenge=None: payload if challenge is None else "")
251
+
252
+
253
+ def connect_smtp(account, *, secret=None):
254
+ secret = _secret(account, "smtp", secret)
255
+ connection = _connection("smtp")
256
+ implicit_tls = account.smtp_security == "tls"
257
+ try:
258
+ conn = _SMTPClient(account.smtp_host, account.smtp_port, connection, implicit_tls)
259
+ except OSError as exc:
260
+ raise _smtp_greeting_error(exc, "GREETING") from None
261
+ try:
262
+ if not implicit_tls:
263
+ _smtp_starttls(conn, connection.context)
264
+ try:
265
+ conn.ehlo_or_helo_if_needed()
266
+ except OSError as exc:
267
+ raise _smtp_greeting_error(exc, "EHLO") from None
268
+ try:
269
+ _smtp_login(conn, account, secret)
270
+ except smtplib.SMTPNotSupportedError:
271
+ raise MailError("The SMTP server does not offer the required authentication method.",
272
+ "smtp", "mailbox_auth", reason="mechanism_unavailable") from None
273
+ except smtplib.SMTPResponseException as exc:
274
+ raise MailError("SMTP authentication failed. Check the mailbox credential and SMTP access.",
275
+ "smtp", "mailbox_auth", reason="rejected", code=exc.smtp_code) from None
276
+ except UnicodeError:
277
+ raise MailError("The SMTP authentication method cannot encode the configured credential.",
278
+ "smtp", "mailbox_auth", reason="invalid_credential_encoding") from None
279
+ except OSError:
280
+ raise MailError("SMTP authentication could not be completed.", "smtp", "mailbox_auth",
281
+ reason="authentication_failed") from None
282
+ LOG.debug("protocol=smtp stage=mailbox_auth outcome=authenticated")
283
+ return conn
284
+ except BaseException:
285
+ with suppress(OSError):
286
+ conn.close()
287
+ raise
288
+
289
+
290
+ def check_protocol(account, protocol, *, secret=None):
291
+ if protocol == "imap":
292
+ conn = connect_imap(account, secret=secret)
293
+ with suppress(OSError, imaplib.IMAP4.error):
294
+ conn.logout()
295
+ elif protocol == "smtp":
296
+ conn = connect_smtp(account, secret=secret)
297
+ try:
298
+ with suppress(OSError, smtplib.SMTPException):
299
+ conn.quit()
300
+ finally:
301
+ conn.close()
302
+ else:
303
+ raise MacoError("Choose an IMAP or SMTP connection to check.")
@@ -0,0 +1,66 @@
1
+ Metadata-Version: 2.4
2
+ Name: maco-cli
3
+ Version: 0.4.5
4
+ Summary: An agent-friendly IMAP and SMTP command-line client
5
+ Requires-Python: >=3.9
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: cryptography>=42
8
+
9
+ # Maco CLI
10
+
11
+ Maco CLI lets an Agent read, search, organize, and send mail using IMAP/SMTP, the Gmail API, or Microsoft Graph. Mailbox access is granted through Maco Mail Helper.
12
+
13
+ ## Install or upgrade
14
+
15
+ Activate a virtual environment with Python 3.9 or later and run:
16
+
17
+ ```sh
18
+ python -m pip install --upgrade -r https://macomail.app/cli/downloads/install.txt
19
+ maco --version
20
+ ```
21
+
22
+ The Maco installation manifest pins the wheel and its SHA-256 checksum.
23
+
24
+ ## Connect an Agent
25
+
26
+ Run `maco account login --start` on the machine where the Agent runs. Open the returned authorization link, verify the code, and choose the mailboxes and permissions to grant. In the same environment, run `maco account login --finish <request_id>`, followed by `maco accounts`.
27
+
28
+ ## List and search messages
29
+
30
+ ```sh
31
+ maco emails --account work --after 2026-11-01 --before 2026-12-01
32
+ maco search --account travel "hotel reservation OR train ticket"
33
+ maco search --account qq-profile --strict --match subject "search phrase"
34
+ ```
35
+
36
+ `emails` and `search` accept both date flags. `--after` starts the range and `--before` excludes the ending date. Gmail and Outlook use UTC for the received date. IMAP uses the calendar date of the server's internal timestamp.
37
+
38
+ Each side of uppercase `OR` is a literal phrase. Double quotes within the query keep a literal `OR` together with the enclosing phrase.
39
+
40
+ Gmail search verifies indexed candidates locally, ranks subject and sender matches first, and reads bodies as needed to fill the page. Use `--native` for Gmail's indexed results directly. `--strict` verifies up to 100 candidates for any provider. Use `--match subject`, `--match from`, or `--match body` to select a field. The `matched_fields` array identifies verified fields. `strict.more_candidates` indicates that additional candidates or bodies were outside the verification performed for this result. IMAP reads use `BODY.PEEK` in a read-only session.
41
+
42
+ Outlook sends sender and subject restrictions to Microsoft Graph's search index. Graph indexes words, names, and addresses according to Outlook search syntax. Provider queries share a 30-second request budget across pages and retries. An exhausted budget returns a JSON timeout error. Outlook marks incomplete results at the 1,000-row indexed limit with `truncated`.
43
+
44
+ Read `messages[].id` and `messages[].folder` for all account types. IMAP responses also expose `emails`, `uid`, and `uidvalidity`. Pass the IMAP folder and UIDVALIDITY from the response when reading or acting on those messages.
45
+
46
+ ## Configure an IMAP/SMTP proxy
47
+
48
+ Save a proxy once for this operating system user and Maco configuration directory.
49
+
50
+ ```sh
51
+ maco proxy set http://127.0.0.1:8080
52
+ maco proxy show
53
+ maco proxy clear
54
+ ```
55
+
56
+ `maco proxy set` without a URL saves the proxy from the current environment. Use this form when the URL includes credentials. Maco uses a private file on macOS and Linux and DPAPI on Windows. The command output shows only the proxy scheme, host, and port.
57
+
58
+ Maco checks `MACO_MAIL_PROXY`, the saved setting, then `ALL_PROXY` and `HTTPS_PROXY`. Lowercase names take precedence over conflicting uppercase names. `NO_PROXY` accepts hostname suffixes and optional ports. `MACO_MAIL_PROXY=direct` forces a direct connection for the current environment. `maco proxy set direct` saves that choice for future terminals.
59
+
60
+ With `ALL_PROXY` or `HTTPS_PROXY`, Maco uses that proxy immediately when mail DNS returns an address in `198.18.0.0/15`. Otherwise, a direct TCP or implicit TLS connectivity failure gets one proxy retry. Authentication and certificate verification errors are reported directly. The last successful route is cached per server and port for 24 hours in the Maco configuration directory.
61
+
62
+ `http://` uses CONNECT. Both `socks5://` and `socks5h://` pass the original hostname to the proxy. TLS SNI and certificate validation use the configured mail server name. Gmail API and Outlook Graph use their own HTTPS connection settings.
63
+
64
+ `maco auth check` reports `"via": "direct"` or `"via": "proxy"` for IMAP/SMTP. `maco account login --finish` reports the route for each mailbox checked during that run. When either protocol uses a proxy, the result shows `"via": "proxy"` with a `proxy` value containing its scheme, host, and port. Failed retries include the stage and reason of each attempt.
65
+
66
+ Get started at [Maco Mail Helper](https://macomail.app/cli/).
@@ -0,0 +1,24 @@
1
+ maco_cli/__init__.py,sha256=pZllzYeY0SO5P1diWx1nRJVJ2QQ_yIK6MTsxPlDNnaM,47
2
+ maco_cli/__main__.py,sha256=MHKZ_ae3fSLGTLUUMOx15fWdeOnJSHhq-zslRP5F5Lc,79
3
+ maco_cli/accounts.py,sha256=zbNY7Y3FDgAI0VaR2JsJfoCFTGL7Mc2FBAIKXBKTu-4,15376
4
+ maco_cli/cli.py,sha256=WIKN4uS9bOjnMVY_OFIFD0eAojWO7oU85IUWkJPOEZE,24731
5
+ maco_cli/device_login.py,sha256=Vnudm_q8pL4brQK-zJrTy8uZwbJmaAIv6Uqqf0SKeHA,9050
6
+ maco_cli/device_store.py,sha256=cdk-c1cS7Gx-i2sBt6SiWhG_IZC2MeYQStbHU2nbQ4w,2789
7
+ maco_cli/errors.py,sha256=h5_OPPBm0B1qTysMg1Y8tVkj0lYWhx1jx1qSeoy73HA,372
8
+ maco_cli/gmail_api.py,sha256=iLbZds4xPIzKbcjpBTA19ru2B0X3L3uz9zm-b1Dr-d8,9935
9
+ maco_cli/graph_api.py,sha256=l8klzHTJCM46dGy85hHH42uTW1iPt7eKE0xEKd6n7vU,12088
10
+ maco_cli/helper_client.py,sha256=550G1f4All3opHQk3gf98B1r0LbLXxBQ9wydFh66AyE,9447
11
+ maco_cli/incoming.py,sha256=JAsU6zjHyaX2p6rxP7DhlGKSeSUS0Vr-eSpu3BqxI3w,17992
12
+ maco_cli/mail_query.py,sha256=4vXPkJ0oaE2acYClXrpa78awCWkD-mkkuEdZJxQa-vM,1213
13
+ maco_cli/mail_socket.py,sha256=ca5DEnsSzzz-gONkE0Bp6FV4A7lKYglVWNfOE0nuvug,16952
14
+ maco_cli/message_text.py,sha256=5lYvc4Wcep-hTlzdJS0_BsDavDnRhbdvMVaNXQwTgDs,1577
15
+ maco_cli/oauth.py,sha256=QB4Q3Jklphr9naTMTdlRr_ppMWHiCYqDq4FoMk0Qp_o,5848
16
+ maco_cli/outgoing.py,sha256=XX8WQqd2zTUkKsU3vcswFVE_jhMNCfGfgf0Gx8zA87Y,9030
17
+ maco_cli/provider.py,sha256=VxiClp4JSQdZN0kjdyWtDZQBMvExqBIfr9Y62Bu2_Iw,13476
18
+ maco_cli/strict_search.py,sha256=osL5V2dPhHEEAWMco5DusfoT1W-1CZT1UfUl7cZyAsc,3752
19
+ maco_cli/transport.py,sha256=TQO-kNnRKhpBOETqNOVWI9yD9rB_I8Eb-q_UZhkjpCM,12176
20
+ maco_cli-0.4.5.dist-info/METADATA,sha256=zEI0rd6HgYJHgr3OxkvKZOSlLBgfZPib28hqEoOUQ2c,4581
21
+ maco_cli-0.4.5.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
22
+ maco_cli-0.4.5.dist-info/entry_points.txt,sha256=JdYBVhPkc837vUIBLUaDyHPzN4mPA1HZpxhNPONFrTU,72
23
+ maco_cli-0.4.5.dist-info/top_level.txt,sha256=rAmm70uxBTccZE8CrNNgkEAfGuev_JBY0CEgfGA4zDc,9
24
+ maco_cli-0.4.5.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ maco = maco_cli.cli:main
3
+ maco-cli = maco_cli.cli:main
@@ -0,0 +1 @@
1
+ maco_cli