@caddis/cli 0.4.101 → 0.4.103
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.
- package/README.md +8 -0
- package/bundles/antigravity-plugin/plugin.json +1 -1
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_exit.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_file_lock.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_frontmatter.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_redact.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_roadmap.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_rows.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_status.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_tidy.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_todo.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_workstreams.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_worktree_safety.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/caddis_guide.json +9 -9
- package/bundles/antigravity-plugin/scripts/caddis_todo.py +9 -3
- package/bundles/antigravity-plugin/skills/_registry.md +2 -1
- package/bundles/antigravity-plugin/skills/graph-email/SKILL.md +3 -3
- package/bundles/{antigravity-plugin-extras/skills/graph-email → antigravity-plugin/skills/send-email}/SKILL.md +9 -2
- package/bundles/{antigravity-plugin-extras/skills/graph-email → antigravity-plugin/skills/send-email}/email.toml.example +1 -1
- package/bundles/antigravity-plugin-extras/plugin.json +1 -1
- package/bundles/antigravity-plugin-extras/skills/_registry.md +0 -1
- package/bundles/codex/.codex/skills/devops/send-email/SKILL.md +60 -0
- package/bundles/codex/.codex/skills/devops/send-email/email.toml.example +44 -0
- package/bundles/codex/.codex/skills/devops/send-email/scripts/send_email.py +432 -0
- package/bundles/manifest.json +3 -3
- package/dist/cli.js +894 -234
- package/dist/export/assets/{export-or4yLaQm.css → export-DKXFSE8J.css} +1 -1
- package/dist/export/index.html +2 -2
- package/dist/ui/assets/{Activity-BH0Scw-H.js → Activity-B816JVqx.js} +1 -1
- package/dist/ui/assets/{Guide-f5f2DrlU.js → Guide-CnL1DiTr.js} +1 -1
- package/dist/ui/assets/Palette-BKM_A64G.js +11 -0
- package/dist/ui/assets/{RoadmapTab-BqLBt4fW.js → RoadmapTab-DhC4-kqv.js} +1 -1
- package/dist/ui/assets/{external-link-BFMu4CXk.js → external-link-DagTFCsV.js} +1 -1
- package/dist/ui/assets/index-Bj5qA-fq.js +226 -0
- package/dist/ui/assets/{index-h1dmppYX.css → index-FqnApO4t.css} +1 -1
- package/dist/ui/index.html +2 -2
- package/package.json +1 -1
- package/dist/ui/assets/Palette-cTwLWgn4.js +0 -11
- package/dist/ui/assets/index-39J2d1qv.js +0 -226
- /package/bundles/{antigravity-plugin-extras/skills/graph-email → antigravity-plugin/skills/send-email}/scripts/send_email.py +0 -0
- /package/dist/export/assets/{export-Cb3BXZCo.js → export-B1Le4b3E.js} +0 -0
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Send one email with Microsoft Graph (sendMail, client credentials) or SMTP.
|
|
3
|
+
|
|
4
|
+
Settings come from three places. The first one that has a value wins:
|
|
5
|
+
1. a command-line flag
|
|
6
|
+
2. an environment variable (CADDIS_EMAIL_*)
|
|
7
|
+
3. the config file ~/.caddis/email.toml (see email.toml.example)
|
|
8
|
+
|
|
9
|
+
Secrets (Graph client secret, SMTP password) are never read from the config file. They come from
|
|
10
|
+
the process environment or from the env file named by `env_file`. The script never prints a
|
|
11
|
+
secret or a token. Errors show the provider, the HTTP or SMTP status code and the error name only.
|
|
12
|
+
|
|
13
|
+
Exit codes: 0 done, 1 provider error, 2 missing or invalid setting.
|
|
14
|
+
Standard library only.
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import argparse
|
|
19
|
+
import base64
|
|
20
|
+
import html
|
|
21
|
+
import json
|
|
22
|
+
import mimetypes
|
|
23
|
+
import os
|
|
24
|
+
import re
|
|
25
|
+
import smtplib
|
|
26
|
+
import ssl
|
|
27
|
+
import sys
|
|
28
|
+
import urllib.error
|
|
29
|
+
import urllib.parse
|
|
30
|
+
import urllib.request
|
|
31
|
+
from dataclasses import dataclass
|
|
32
|
+
from email.message import EmailMessage
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
|
|
35
|
+
import tomllib
|
|
36
|
+
|
|
37
|
+
PROVIDERS = ("graph", "smtp")
|
|
38
|
+
SECURITY = ("starttls", "ssl", "none")
|
|
39
|
+
SMTP_PORTS = {"starttls": 587, "ssl": 465, "none": 25}
|
|
40
|
+
DEFAULT_GRAPH_KEYS = ("ALERT_GRAPH_TENANT_ID", "ALERT_GRAPH_CLIENT_ID", "ALERT_GRAPH_CLIENT_SECRET")
|
|
41
|
+
DEFAULT_SMTP_PASSWORD_KEY = "EMAIL_SMTP_PASSWORD"
|
|
42
|
+
STYLE = "font-family:Segoe UI,Arial,sans-serif;font-size:14px;line-height:1.5;color:#222"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class ConfigError(Exception):
|
|
46
|
+
"""A setting is invalid. The message never holds a secret."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
# ---------------------------------------------------------------- markdown
|
|
50
|
+
|
|
51
|
+
def extract_section(md: str) -> str:
|
|
52
|
+
md = re.sub(r"\A---\n.*?\n---\n", "", md, flags=re.DOTALL)
|
|
53
|
+
m = re.search(r"<!-- email-start -->(.*?)<!-- email-end -->", md, flags=re.DOTALL)
|
|
54
|
+
return m.group(1) if m else md
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def inline(text: str) -> str:
|
|
58
|
+
text = html.escape(text)
|
|
59
|
+
text = re.sub(r"\*\*(.+?)\*\*", r"<b>\1</b>", text)
|
|
60
|
+
return re.sub(r"`(.+?)`", r"<code>\1</code>", text)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def md_to_html(md: str) -> str:
|
|
64
|
+
md = extract_section(md)
|
|
65
|
+
out, para, lines, i = [], [], md.splitlines(), 0
|
|
66
|
+
|
|
67
|
+
def flush():
|
|
68
|
+
if para:
|
|
69
|
+
out.append("<p>" + " ".join(inline(p) for p in para) + "</p>")
|
|
70
|
+
para.clear()
|
|
71
|
+
|
|
72
|
+
def cells(row):
|
|
73
|
+
return [c.strip() for c in row.strip("|").split("|")]
|
|
74
|
+
|
|
75
|
+
while i < len(lines):
|
|
76
|
+
s = lines[i].strip()
|
|
77
|
+
if not s:
|
|
78
|
+
flush()
|
|
79
|
+
elif s == "---":
|
|
80
|
+
flush()
|
|
81
|
+
out.append("<hr>")
|
|
82
|
+
elif s.startswith("#"):
|
|
83
|
+
flush()
|
|
84
|
+
n = min(len(s) - len(s.lstrip("#")), 4)
|
|
85
|
+
out.append(f"<h{n}>{inline(s.lstrip('#').strip())}</h{n}>")
|
|
86
|
+
elif s.startswith("|") and i + 1 < len(lines) and re.match(r"^\|[\s:|-]+\|$", lines[i + 1].strip()):
|
|
87
|
+
flush()
|
|
88
|
+
rows = [s]
|
|
89
|
+
i += 2
|
|
90
|
+
while i < len(lines) and lines[i].strip().startswith("|"):
|
|
91
|
+
rows.append(lines[i].strip())
|
|
92
|
+
i += 1
|
|
93
|
+
i -= 1
|
|
94
|
+
t = '<table style="border-collapse:collapse" border="1" cellpadding="6"><tr>'
|
|
95
|
+
t += "".join(f"<th>{inline(c)}</th>" for c in cells(rows[0])) + "</tr>"
|
|
96
|
+
for r in rows[1:]:
|
|
97
|
+
t += "<tr>" + "".join(f"<td>{inline(c)}</td>" for c in cells(r)) + "</tr>"
|
|
98
|
+
out.append(t + "</table>")
|
|
99
|
+
elif re.match(r"^[-*] ", s):
|
|
100
|
+
flush()
|
|
101
|
+
items = []
|
|
102
|
+
while i < len(lines) and re.match(r"^\s*[-*] ", lines[i]):
|
|
103
|
+
item = re.sub(r"^\s*[-*] ", "", lines[i])
|
|
104
|
+
i += 1
|
|
105
|
+
while (i < len(lines) and lines[i].startswith(" ") and lines[i].strip()
|
|
106
|
+
and not re.match(r"^\s*[-*] ", lines[i])):
|
|
107
|
+
item += " " + lines[i].strip()
|
|
108
|
+
i += 1
|
|
109
|
+
items.append(f"<li>{inline(item)}</li>")
|
|
110
|
+
i -= 1
|
|
111
|
+
out.append("<ul>" + "".join(items) + "</ul>")
|
|
112
|
+
else:
|
|
113
|
+
para.append(s)
|
|
114
|
+
i += 1
|
|
115
|
+
flush()
|
|
116
|
+
return f'<div style="{STYLE}">' + "\n".join(out) + "</div>"
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
# ---------------------------------------------------------------- config
|
|
120
|
+
|
|
121
|
+
@dataclass
|
|
122
|
+
class Config:
|
|
123
|
+
provider: str = "graph"
|
|
124
|
+
sender: str = ""
|
|
125
|
+
env_file: str = ""
|
|
126
|
+
# graph: names of the keys that hold the secrets (not the secrets)
|
|
127
|
+
tenant_key: str = DEFAULT_GRAPH_KEYS[0]
|
|
128
|
+
client_id_key: str = DEFAULT_GRAPH_KEYS[1]
|
|
129
|
+
client_secret_key: str = DEFAULT_GRAPH_KEYS[2]
|
|
130
|
+
# smtp
|
|
131
|
+
smtp_host: str = ""
|
|
132
|
+
smtp_port: int = 0
|
|
133
|
+
smtp_security: str = "starttls"
|
|
134
|
+
smtp_username: str = ""
|
|
135
|
+
smtp_password_key: str = DEFAULT_SMTP_PASSWORD_KEY
|
|
136
|
+
smtp_timeout: float = 30.0
|
|
137
|
+
smtp_allow_insecure_auth: bool = False
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def config_path(flag: str | None) -> Path:
|
|
141
|
+
chosen = flag or os.environ.get("CADDIS_EMAIL_CONFIG")
|
|
142
|
+
return Path(chosen).expanduser() if chosen else Path.home() / ".caddis" / "email.toml"
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def read_toml(path: Path) -> dict:
|
|
146
|
+
if not path.is_file():
|
|
147
|
+
return {}
|
|
148
|
+
try:
|
|
149
|
+
return tomllib.loads(path.read_text(encoding="utf-8"))
|
|
150
|
+
except (tomllib.TOMLDecodeError, OSError, UnicodeDecodeError) as e:
|
|
151
|
+
raise ConfigError(f"cannot read config file ({type(e).__name__})") from None
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def read_env(path: Path) -> dict:
|
|
155
|
+
out = {}
|
|
156
|
+
for line in path.read_text(encoding="utf-8").splitlines():
|
|
157
|
+
line = line.strip()
|
|
158
|
+
if not line or line.startswith("#") or "=" not in line:
|
|
159
|
+
continue
|
|
160
|
+
k, v = line.split("=", 1)
|
|
161
|
+
out[k.strip()] = v.strip().strip('"').strip("'")
|
|
162
|
+
return out
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _pick(flag, env_names, file_value, default=""):
|
|
166
|
+
"""flag, then the first set env var, then the config file value, then the default."""
|
|
167
|
+
if flag not in (None, ""):
|
|
168
|
+
return flag
|
|
169
|
+
for name in env_names:
|
|
170
|
+
v = os.environ.get(name)
|
|
171
|
+
if v:
|
|
172
|
+
return v
|
|
173
|
+
if file_value not in (None, ""):
|
|
174
|
+
return file_value
|
|
175
|
+
return default
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _number(value, name, cast):
|
|
179
|
+
try:
|
|
180
|
+
return cast(value)
|
|
181
|
+
except (TypeError, ValueError):
|
|
182
|
+
raise ConfigError(f"{name} must be a number") from None
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def load_config(a: argparse.Namespace) -> Config:
|
|
186
|
+
f = read_toml(config_path(a.config))
|
|
187
|
+
g, s = f.get("graph", {}) or {}, f.get("smtp", {}) or {}
|
|
188
|
+
c = Config()
|
|
189
|
+
c.provider = str(_pick(a.provider, ["CADDIS_EMAIL_PROVIDER"], f.get("provider"), "graph")).lower()
|
|
190
|
+
if c.provider not in PROVIDERS:
|
|
191
|
+
raise ConfigError(f"provider must be one of {', '.join(PROVIDERS)}")
|
|
192
|
+
c.sender = _pick(a.sender, ["CADDIS_EMAIL_SENDER", "GRAPH_EMAIL_SENDER"], f.get("sender"))
|
|
193
|
+
c.env_file = _pick(a.env_file, ["CADDIS_EMAIL_ENV_FILE", "GRAPH_EMAIL_ENV_FILE"], f.get("env_file"))
|
|
194
|
+
c.tenant_key = g.get("tenant_id_key") or c.tenant_key
|
|
195
|
+
c.client_id_key = g.get("client_id_key") or c.client_id_key
|
|
196
|
+
c.client_secret_key = g.get("client_secret_key") or c.client_secret_key
|
|
197
|
+
c.smtp_host = _pick(a.smtp_host, ["CADDIS_EMAIL_SMTP_HOST"], s.get("host"))
|
|
198
|
+
c.smtp_security = str(_pick(a.smtp_security, ["CADDIS_EMAIL_SMTP_SECURITY"], s.get("security"),
|
|
199
|
+
"starttls")).lower()
|
|
200
|
+
if c.smtp_security not in SECURITY:
|
|
201
|
+
raise ConfigError(f"smtp security must be one of {', '.join(SECURITY)}")
|
|
202
|
+
port = _pick(a.smtp_port, ["CADDIS_EMAIL_SMTP_PORT"], s.get("port"), SMTP_PORTS[c.smtp_security])
|
|
203
|
+
c.smtp_port = _number(port, "smtp port", int)
|
|
204
|
+
c.smtp_username = _pick(a.smtp_username, ["CADDIS_EMAIL_SMTP_USERNAME"], s.get("username"))
|
|
205
|
+
c.smtp_password_key = s.get("password_key") or c.smtp_password_key
|
|
206
|
+
c.smtp_timeout = _number(_pick(a.smtp_timeout, ["CADDIS_EMAIL_SMTP_TIMEOUT"], s.get("timeout"), 30),
|
|
207
|
+
"smtp timeout", float)
|
|
208
|
+
# Only a real TOML boolean true opts in; a string such as "true" does not.
|
|
209
|
+
c.smtp_allow_insecure_auth = s.get("allow_insecure_auth") is True
|
|
210
|
+
return c
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def check_smtp_security(cfg: Config) -> None:
|
|
214
|
+
"""Refuse a login (username or password) over security "none" unless the user opted in.
|
|
215
|
+
|
|
216
|
+
The message names settings only. It never holds a username, a password or a host.
|
|
217
|
+
"""
|
|
218
|
+
if cfg.provider != "smtp" or cfg.smtp_security != "none" or cfg.smtp_allow_insecure_auth:
|
|
219
|
+
return
|
|
220
|
+
if cfg.smtp_username or get_secret(cfg, cfg.smtp_password_key):
|
|
221
|
+
raise ConfigError('smtp security is off and a login is set, so the login would go in clear text; '
|
|
222
|
+
'set security to "starttls" or "ssl"')
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _env_file_values(cfg: Config) -> dict:
|
|
226
|
+
if not cfg.env_file:
|
|
227
|
+
return {}
|
|
228
|
+
try:
|
|
229
|
+
return read_env(Path(cfg.env_file).expanduser())
|
|
230
|
+
except (OSError, UnicodeDecodeError):
|
|
231
|
+
return {}
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def get_secret(cfg: Config, key: str) -> str:
|
|
235
|
+
"""The process environment first, then the env file. Never the config file."""
|
|
236
|
+
return os.environ.get(key) or _env_file_values(cfg).get(key, "")
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def missing_settings(cfg: Config) -> list[str]:
|
|
240
|
+
"""Names of settings that are not set. Never a value."""
|
|
241
|
+
miss = []
|
|
242
|
+
if not cfg.sender:
|
|
243
|
+
miss.append("sender")
|
|
244
|
+
if cfg.provider == "graph":
|
|
245
|
+
keys = (cfg.tenant_key, cfg.client_id_key, cfg.client_secret_key)
|
|
246
|
+
else:
|
|
247
|
+
if not cfg.smtp_host:
|
|
248
|
+
miss.append("smtp.host")
|
|
249
|
+
keys = (cfg.smtp_password_key,) if cfg.smtp_username else ()
|
|
250
|
+
absent = [k for k in keys if not get_secret(cfg, k)]
|
|
251
|
+
if absent:
|
|
252
|
+
miss.extend(["env_file"] if not cfg.env_file else absent)
|
|
253
|
+
return miss
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
# ---------------------------------------------------------------- attachments and messages
|
|
257
|
+
|
|
258
|
+
def _ctype(name: str) -> str:
|
|
259
|
+
return mimetypes.guess_type(name)[0] or "application/octet-stream"
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def build_graph_payload(subject, html_body, to, attach_paths) -> dict:
|
|
263
|
+
attachments = []
|
|
264
|
+
for p in attach_paths:
|
|
265
|
+
pp = Path(p)
|
|
266
|
+
attachments.append({
|
|
267
|
+
"@odata.type": "#microsoft.graph.fileAttachment", "name": pp.name,
|
|
268
|
+
"contentType": _ctype(pp.name),
|
|
269
|
+
"contentBytes": base64.b64encode(pp.read_bytes()).decode(),
|
|
270
|
+
})
|
|
271
|
+
return {"message": {
|
|
272
|
+
"subject": subject, "body": {"contentType": "HTML", "content": html_body},
|
|
273
|
+
"toRecipients": [{"emailAddress": {"address": t}} for t in to],
|
|
274
|
+
"attachments": attachments}, "saveToSentItems": True}
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def build_smtp_message(sender, to, subject, plain, html_body, attach_paths) -> EmailMessage:
|
|
278
|
+
msg = EmailMessage()
|
|
279
|
+
msg["From"], msg["To"], msg["Subject"] = sender, ", ".join(to), subject
|
|
280
|
+
msg.set_content(plain)
|
|
281
|
+
msg.add_alternative(html_body, subtype="html")
|
|
282
|
+
for p in attach_paths:
|
|
283
|
+
pp = Path(p)
|
|
284
|
+
main, _, sub = _ctype(pp.name).partition("/")
|
|
285
|
+
msg.add_attachment(pp.read_bytes(), maintype=main, subtype=sub or "octet-stream", filename=pp.name)
|
|
286
|
+
return msg
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
# ---------------------------------------------------------------- senders
|
|
290
|
+
|
|
291
|
+
def post(url: str, data: bytes, headers: dict, timeout: float = 30):
|
|
292
|
+
req = urllib.request.Request(url, data=data, headers=headers, method="POST")
|
|
293
|
+
try:
|
|
294
|
+
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
295
|
+
return r.status, r.read()
|
|
296
|
+
except urllib.error.HTTPError as e:
|
|
297
|
+
return e.code, e.read()
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _err_name(raw: bytes) -> str:
|
|
301
|
+
try:
|
|
302
|
+
err = json.loads(raw or b"{}").get("error", "unknown")
|
|
303
|
+
except (ValueError, AttributeError):
|
|
304
|
+
return "unknown"
|
|
305
|
+
if isinstance(err, dict):
|
|
306
|
+
err = err.get("code", "unknown")
|
|
307
|
+
return str(err) if re.fullmatch(r"[A-Za-z0-9_.-]{1,64}", str(err)) else "unknown"
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def send_graph(cfg: Config, a, html_body: str) -> int:
|
|
311
|
+
tenant = get_secret(cfg, cfg.tenant_key)
|
|
312
|
+
tok_url = f"https://login.microsoftonline.com/{urllib.parse.quote(tenant)}/oauth2/v2.0/token"
|
|
313
|
+
form = urllib.parse.urlencode({
|
|
314
|
+
"client_id": get_secret(cfg, cfg.client_id_key), "client_secret": get_secret(cfg, cfg.client_secret_key),
|
|
315
|
+
"scope": "https://graph.microsoft.com/.default", "grant_type": "client_credentials",
|
|
316
|
+
}).encode()
|
|
317
|
+
try:
|
|
318
|
+
status, raw = post(tok_url, form, {"Content-Type": "application/x-www-form-urlencoded"})
|
|
319
|
+
if status != 200:
|
|
320
|
+
print(f"error: provider graph, token request failed, HTTP {status}, {_err_name(raw)}", file=sys.stderr)
|
|
321
|
+
return 1
|
|
322
|
+
token = json.loads(raw)["access_token"]
|
|
323
|
+
payload = build_graph_payload(a.subject, html_body, a.to, a.attach)
|
|
324
|
+
url = f"https://graph.microsoft.com/v1.0/users/{urllib.parse.quote(cfg.sender)}/sendMail"
|
|
325
|
+
status, raw = post(url, json.dumps(payload).encode(),
|
|
326
|
+
{"Authorization": f"Bearer {token}", "Content-Type": "application/json"})
|
|
327
|
+
except (OSError, ValueError, KeyError) as e:
|
|
328
|
+
print(f"error: provider graph, request failed, {type(e).__name__}", file=sys.stderr)
|
|
329
|
+
return 1
|
|
330
|
+
if status == 202:
|
|
331
|
+
print(f"sent: provider graph, HTTP 202 (accepted for delivery) to {', '.join(a.to)} subject '{a.subject}'")
|
|
332
|
+
return 0
|
|
333
|
+
print(f"error: provider graph, sendMail failed, HTTP {status}, {_err_name(raw)}", file=sys.stderr)
|
|
334
|
+
return 1
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def send_smtp(cfg: Config, a, html_body: str, plain: str) -> int:
|
|
338
|
+
try:
|
|
339
|
+
msg = build_smtp_message(cfg.sender, a.to, a.subject, plain, html_body, a.attach)
|
|
340
|
+
password = get_secret(cfg, cfg.smtp_password_key) if cfg.smtp_username else ""
|
|
341
|
+
# smtplib's own default context does not check the certificate; this one does.
|
|
342
|
+
ctx = ssl.create_default_context()
|
|
343
|
+
if cfg.smtp_security == "ssl":
|
|
344
|
+
conn = smtplib.SMTP_SSL(cfg.smtp_host, cfg.smtp_port, timeout=cfg.smtp_timeout, context=ctx)
|
|
345
|
+
else:
|
|
346
|
+
conn = smtplib.SMTP(cfg.smtp_host, cfg.smtp_port, timeout=cfg.smtp_timeout)
|
|
347
|
+
with conn as s:
|
|
348
|
+
if cfg.smtp_security == "starttls":
|
|
349
|
+
s.ehlo()
|
|
350
|
+
s.starttls(context=ctx)
|
|
351
|
+
s.ehlo()
|
|
352
|
+
if cfg.smtp_username:
|
|
353
|
+
s.login(cfg.smtp_username, password)
|
|
354
|
+
s.send_message(msg)
|
|
355
|
+
except smtplib.SMTPResponseException as e:
|
|
356
|
+
print(f"error: provider smtp, SMTP {e.smtp_code}, {type(e).__name__}", file=sys.stderr)
|
|
357
|
+
return 1
|
|
358
|
+
except (smtplib.SMTPException, OSError) as e:
|
|
359
|
+
print(f"error: provider smtp, {type(e).__name__}", file=sys.stderr)
|
|
360
|
+
return 1
|
|
361
|
+
print(f"sent: provider smtp, accepted by server for {', '.join(a.to)} subject '{a.subject}'")
|
|
362
|
+
return 0
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
# ---------------------------------------------------------------- cli
|
|
366
|
+
|
|
367
|
+
def parse_args(argv=None) -> argparse.Namespace:
|
|
368
|
+
ap = argparse.ArgumentParser(description="Send one email with Microsoft Graph or SMTP.")
|
|
369
|
+
ap.add_argument("--to", action="append")
|
|
370
|
+
ap.add_argument("--subject")
|
|
371
|
+
ap.add_argument("--body-file")
|
|
372
|
+
ap.add_argument("--attach", action="append", default=[])
|
|
373
|
+
ap.add_argument("--dry-run", action="store_true", help="write <body>.preview.html, send nothing")
|
|
374
|
+
ap.add_argument("--check", action="store_true", help="validate settings, send nothing, print no secret")
|
|
375
|
+
ap.add_argument("--config", help="config file (default ~/.caddis/email.toml)")
|
|
376
|
+
ap.add_argument("--provider")
|
|
377
|
+
ap.add_argument("--sender")
|
|
378
|
+
ap.add_argument("--env-file")
|
|
379
|
+
ap.add_argument("--smtp-host")
|
|
380
|
+
ap.add_argument("--smtp-port")
|
|
381
|
+
ap.add_argument("--smtp-security")
|
|
382
|
+
ap.add_argument("--smtp-username")
|
|
383
|
+
ap.add_argument("--smtp-timeout")
|
|
384
|
+
a = ap.parse_args(argv)
|
|
385
|
+
if not a.check and not (a.to and a.subject and a.body_file):
|
|
386
|
+
ap.error("--to, --subject and --body-file are required (unless --check)")
|
|
387
|
+
return a
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def check(cfg: Config) -> int:
|
|
391
|
+
miss = missing_settings(cfg)
|
|
392
|
+
print(f"provider: {cfg.provider}")
|
|
393
|
+
print(f"sender: {'set' if cfg.sender else 'MISSING'}")
|
|
394
|
+
if cfg.provider == "smtp":
|
|
395
|
+
print(f"smtp: host {'set' if cfg.smtp_host else 'MISSING'}, port {cfg.smtp_port}, "
|
|
396
|
+
f"security {cfg.smtp_security}, login {'yes' if cfg.smtp_username else 'no'}")
|
|
397
|
+
if miss:
|
|
398
|
+
print(f"missing: {', '.join(miss)}")
|
|
399
|
+
return 2
|
|
400
|
+
print("check ok: all settings and credentials are present (nothing sent)")
|
|
401
|
+
return 0
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def main(argv=None) -> int:
|
|
405
|
+
a = parse_args(argv)
|
|
406
|
+
if a.dry_run and not a.check:
|
|
407
|
+
body = md_to_html(Path(a.body_file).read_text(encoding="utf-8"))
|
|
408
|
+
out = Path(a.body_file).with_suffix(".preview.html")
|
|
409
|
+
out.write_text(f"<html><body>{body}</body></html>", encoding="utf-8")
|
|
410
|
+
print(f"dry run: preview written to {out}; nothing sent")
|
|
411
|
+
return 0
|
|
412
|
+
try:
|
|
413
|
+
cfg = load_config(a)
|
|
414
|
+
check_smtp_security(cfg)
|
|
415
|
+
except ConfigError as e:
|
|
416
|
+
print(f"error: {e}", file=sys.stderr)
|
|
417
|
+
return 2
|
|
418
|
+
if a.check:
|
|
419
|
+
return check(cfg)
|
|
420
|
+
miss = missing_settings(cfg)
|
|
421
|
+
if miss:
|
|
422
|
+
print(f"error: missing settings for provider {cfg.provider}: {', '.join(miss)}", file=sys.stderr)
|
|
423
|
+
return 2
|
|
424
|
+
md = Path(a.body_file).read_text(encoding="utf-8")
|
|
425
|
+
html_body = md_to_html(md)
|
|
426
|
+
if cfg.provider == "smtp":
|
|
427
|
+
return send_smtp(cfg, a, html_body, extract_section(md).strip())
|
|
428
|
+
return send_graph(cfg, a, html_body)
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
if __name__ == "__main__":
|
|
432
|
+
sys.exit(main())
|
package/bundles/manifest.json
CHANGED