-
Notifications
You must be signed in to change notification settings - Fork 162
Expand file tree
/
Copy pathsend-email-resend.py
More file actions
executable file
ยท244 lines (216 loc) ยท 9.17 KB
/
Copy pathsend-email-resend.py
File metadata and controls
executable file
ยท244 lines (216 loc) ยท 9.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
#!/usr/bin/env python3
"""
send-email-resend.py โ Resend API ๅฏไฟก helper
ๅพ ~/.config/taiwan-md/credentials/resend.key ่ฎ API key๏ผๆฐธ้ ไธๅพ stdin ๆฅใไธ่ค่ฟฐใ
ไธๅฏซ้ฒ log๏ผ๏ผๆ markdown ๆช่ฝๆ HTML email ๅฏๅบใ
Usage:
python3 scripts/tools/send-email-resend.py \\
--to <email> --subject <text> --markdown <path>
Env override:
RESEND_API_KEY (ๅไปฃ่ฎๆช๏ผCI/Routine ็จ)
RESEND_FROM (ๅไปฃ้ ่จญ onboarding@resend.dev)
Exit code: 0 = sent๏ผ้ 0 = fail๏ผๅซ Resend response body ๅฏซ stderr๏ผ
"""
import argparse
import json
import os
import re
import sys
import urllib.request
import urllib.error
from pathlib import Path
DEFAULT_FROM = 'Taiwan.md <onboarding@resend.dev>'
KEY_PATH = Path.home() / ".config/taiwan-md/credentials/resend.key"
RESEND_ENDPOINT = "https://api.resend.com/emails"
def load_key() -> str:
env = os.environ.get("RESEND_API_KEY", "").strip()
if env:
return env
if not KEY_PATH.exists():
print(f"โ Resend key not found: {KEY_PATH}", file=sys.stderr)
print(" Set RESEND_API_KEY env or place key at the path above (chmod 600).", file=sys.stderr)
sys.exit(2)
if KEY_PATH.stat().st_mode & 0o077:
print(f"โ ๏ธ {KEY_PATH} ๆฌ้ๅคชๅฏฌ โ ๅปบ่ญฐ chmod 600", file=sys.stderr)
return KEY_PATH.read_text().strip()
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# Minimal markdown โ HTML๏ผไพ่ณด้ถ๏ผ่ถณๅค email ๆ็๏ผ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def md_to_html(md: str) -> str:
"""Tiny converter: heading / bold / italic / list / link / code / hr / paragraph."""
out: list[str] = []
in_ul = False
in_table = False
table_rows: list[str] = []
def flush_table():
nonlocal in_table, table_rows
if not table_rows:
return
rows = table_rows
# First row = header, second row = separator (skip), rest = body
head = rows[0]
body = rows[2:] if len(rows) >= 2 else []
out.append('<table style="border-collapse:collapse;margin:8px 0">')
cells = [c.strip() for c in head.strip("|").split("|")]
out.append("<thead><tr>")
for c in cells:
out.append(
f'<th style="border:1px solid #ddd;padding:4px 8px;background:#f7f7f7;text-align:left">{inline(c)}</th>'
)
out.append("</tr></thead><tbody>")
for r in body:
cells = [c.strip() for c in r.strip("|").split("|")]
out.append("<tr>")
for c in cells:
out.append(
f'<td style="border:1px solid #ddd;padding:4px 8px">{inline(c)}</td>'
)
out.append("</tr>")
out.append("</tbody></table>")
in_table = False
table_rows = []
def inline(s: str) -> str:
# escape first
s = s.replace("&", "&").replace("<", "<").replace(">", ">")
# **bold**
s = re.sub(r"\*\*([^*]+)\*\*", r"<strong>\1</strong>", s)
# *italic*
s = re.sub(r"(?<!\*)\*([^*\n]+)\*(?!\*)", r"<em>\1</em>", s)
# `code`
s = re.sub(
r"`([^`]+)`",
r'<code style="background:#f3f3f3;padding:1px 4px;border-radius:3px;font-family:monospace">\1</code>',
s,
)
# [text](url)
s = re.sub(
r"\[([^\]]+)\]\(([^)]+)\)",
r'<a href="\2" style="color:#2563eb;text-decoration:underline">\1</a>',
s,
)
return s
for line in md.split("\n"):
# Tables
if line.startswith("|") and line.endswith("|"):
if not in_table:
in_table = True
table_rows = []
table_rows.append(line)
continue
if in_table:
flush_table()
if line.startswith("# "):
if in_ul:
out.append("</ul>")
in_ul = False
out.append(f"<h1 style=\"font-size:22px;margin:16px 0 8px\">{inline(line[2:])}</h1>")
elif line.startswith("## "):
if in_ul:
out.append("</ul>")
in_ul = False
out.append(f"<h2 style=\"font-size:18px;margin:14px 0 6px;color:#111\">{inline(line[3:])}</h2>")
elif line.startswith("### "):
if in_ul:
out.append("</ul>")
in_ul = False
out.append(f"<h3 style=\"font-size:15px;margin:10px 0 4px;color:#333\">{inline(line[4:])}</h3>")
elif line.startswith("- "):
if not in_ul:
out.append("<ul style=\"margin:6px 0;padding-left:22px\">")
in_ul = True
out.append(f"<li style=\"margin:2px 0\">{inline(line[2:])}</li>")
elif line.strip() == "---":
if in_ul:
out.append("</ul>")
in_ul = False
out.append("<hr style=\"border:none;border-top:1px solid #ddd;margin:14px 0\">")
elif line.strip() == "":
if in_ul:
out.append("</ul>")
in_ul = False
# blank โ paragraph break
else:
if in_ul:
out.append("</ul>")
in_ul = False
stripped = line.strip()
# italic-only line (e.g., footer _v1.0 ..._)
if stripped.startswith("_") and stripped.endswith("_") and stripped.count("_") >= 2:
out.append(
f"<p style=\"color:#666;font-size:12px;margin:8px 0\"><em>{inline(stripped[1:-1])}</em></p>"
)
else:
out.append(f"<p style=\"margin:6px 0;line-height:1.6\">{inline(line)}</p>")
if in_ul:
out.append("</ul>")
if in_table:
flush_table()
body = "\n".join(out)
wrapped = (
'<div style="font-family:-apple-system,BlinkMacSystemFont,\'Noto Sans TC\',sans-serif;'
"max-width:720px;margin:0 auto;padding:16px;color:#222\">"
f"{body}"
"</div>"
)
return wrapped
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# Resend POST
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def send(api_key: str, to: str, from_: str, subject: str, html: str, text: str) -> dict:
payload = {
"from": from_,
"to": [to],
"subject": subject,
"html": html,
"text": text,
}
req = urllib.request.Request(
RESEND_ENDPOINT,
data=json.dumps(payload).encode("utf-8"),
method="POST",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
# Resend's Cloudflare edge blocks default Python-urllib UA (returns 1010).
# Identify cleanly so the proxy lets us through.
"User-Agent": "taiwan-md-weekly-report/1.0 (+https://taiwan.md)",
"Accept": "application/json",
},
)
try:
with urllib.request.urlopen(req, timeout=30) as resp:
return {"status": resp.status, "body": json.loads(resp.read().decode())}
except urllib.error.HTTPError as e:
body = e.read().decode("utf-8", errors="replace")
return {"status": e.code, "body": body, "error": str(e)}
except Exception as e:
return {"status": -1, "body": "", "error": str(e)}
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# CLI
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def main():
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--to", required=True)
ap.add_argument("--subject", required=True)
ap.add_argument("--markdown", required=True, help="Path to markdown file")
ap.add_argument("--from", dest="from_", default=os.environ.get("RESEND_FROM", DEFAULT_FROM))
args = ap.parse_args()
md_path = Path(args.markdown)
if not md_path.exists():
print(f"โ markdown file not found: {md_path}", file=sys.stderr)
sys.exit(2)
md = md_path.read_text()
html = md_to_html(md)
api_key = load_key()
print(f"[send-email] to={args.to} subject={args.subject!r} from={args.from_!r}", file=sys.stderr)
result = send(api_key, args.to, args.from_, args.subject, html, md)
print(f"[send-email] status={result['status']}", file=sys.stderr)
body = result.get("body")
if isinstance(body, dict):
print(f"[send-email] response: {json.dumps(body, ensure_ascii=False)}", file=sys.stderr)
else:
print(f"[send-email] response: {body}", file=sys.stderr)
if result["status"] not in (200, 201, 202):
sys.exit(1)
if __name__ == "__main__":
main()