okaytosend 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Okaytosend
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,117 @@
1
+ Metadata-Version: 2.4
2
+ Name: okaytosend
3
+ Version: 0.1.0
4
+ Summary: The pre-send check for AI-written email. Check a marketing email against your own pages and files from the command line or from code.
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://okaytosend.com
7
+ Project-URL: Documentation, https://okaytosend.com/docs
8
+ Keywords: email,marketing,verification,ai-agents,mcp,pre-send,fact-checking,cli
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Topic :: Communications :: Email
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Dynamic: license-file
15
+
16
+ # okaytosend
17
+
18
+ The pre-send check for AI-written email.
19
+
20
+ Okaytosend checks a marketing email against built-in rules and your own pages and files, then answers HOLD with each problem and the line that proves it, or CLEAR. It finds wrong prices and dates, offers with no end, discount maths that doesn't add up, leftover merge tags and dead links. It never sends or changes an email.
21
+
22
+ ## Install
23
+
24
+ ```sh
25
+ pip install okaytosend
26
+ ```
27
+
28
+ This installs the `okaytosend` command and the Python client. Python 3.9 or later; no other dependencies. There is also an npm package with the same command: `npx okaytosend`.
29
+
30
+ You need a key: sign up free at [okaytosend.com/sign-up](https://okaytosend.com/sign-up) (25 checks a month, no card), then go to Settings, API keys.
31
+
32
+ ```sh
33
+ export OKAYTOSEND_API_KEY=ots_live_...
34
+ ```
35
+
36
+ ## Check an email
37
+
38
+ ```sh
39
+ okaytosend check launch.eml --source https://bramble.example/pricing
40
+ ```
41
+
42
+ ```text
43
+ HOLD
44
+ 1. CONTRADICTED: “{{first_name}}” · Okaytosend rule: leftover merge tag: ““{{first_name}}” would reach readers as written.”
45
+ 2. CONTRADICTED: “Was £40, now £30: save 40%” · Okaytosend rule: discount maths: “£40 minus £30 gives a saving of 25%.”
46
+ 3. CONTRADICTED: “Bramble Pro costs £9 a month” · Bramble pricing: “Pro: £19 a month”
47
+ Verified 0 · contradicted 3 · conflicting 0 · unverified 0 · N/A 0
48
+ The person decides whether the email or the source is right.
49
+
50
+ Check 3f2a9c1e-f00d-4e02-91fe-b3ed9842716b · https://okaytosend.com/checks/3f2a9c1e-f00d-4e02-91fe-b3ed9842716b
51
+ ```
52
+
53
+ (Bramble is a fictional company.)
54
+
55
+ The email can be an `.eml`, `.html` or `.txt` file, or `-` to read it from stdin. The built-in rules work with no sources at all.
56
+
57
+ | Option | What it does |
58
+ | --- | --- |
59
+ | `--subject`, `--preheader`, `--from-name` | The email's subject, preview text and sender name. An `.eml` file supplies the subject and sender itself |
60
+ | `--project <name or id>` | The project to check against. Optional when the workspace has one project |
61
+ | `--source <url or file>` | A source for this check only: a public URL, or a local `.txt`, `.md`, `.csv`, `.html` or `.json` file. Repeat it, up to 8 |
62
+ | `--revises <check id>` | The check this one follows. Re-checking a HOLD is free |
63
+ | `--fresh` | Read the sources again instead of reusing a result from the last 24 hours |
64
+ | `--detail full` | The full report |
65
+ | `--json` | The API's answer as JSON |
66
+
67
+ Read a saved check with its ID or report link:
68
+
69
+ ```sh
70
+ okaytosend get https://okaytosend.com/checks/3f2a9c1e-f00d-4e02-91fe-b3ed9842716b
71
+ ```
72
+
73
+ ## Exit codes
74
+
75
+ | Code | Meaning |
76
+ | --- | --- |
77
+ | 0 | CLEAR |
78
+ | 1 | HOLD |
79
+ | 2 | Anything else: refused, out of checks, invalid input, network, or still checking after 3 minutes |
80
+
81
+ So an agent or a CI job can stop on a HOLD: `okaytosend check email.html || exit 1`.
82
+
83
+ ## From code
84
+
85
+ ```python
86
+ import os
87
+ from okaytosend import Okaytosend, OkaytosendError
88
+
89
+ okaytosend = Okaytosend(api_key=os.environ["OKAYTOSEND_API_KEY"])
90
+ check = okaytosend.check(
91
+ subject="Spring sale ends Friday",
92
+ html=email_html,
93
+ sources=[{"title": "Pricing", "url": "https://bramble.example/pricing"}],
94
+ )
95
+
96
+ if check.get("verdict") == "HOLD":
97
+ for finding in check["findings"]:
98
+ print(finding["emailQuote"], "→", (finding.get("source") or {}).get("quote"))
99
+ ```
100
+
101
+ `check()` takes the API's request fields as keyword arguments, waits while a check is still running (up to 3 minutes) and raises `OkaytosendError` with the API's code and message when a check is refused. `get_check(id_or_link)` reads a saved check for free.
102
+
103
+ ## Tell your agent
104
+
105
+ Paste this into CLAUDE.md, AGENTS.md, your Cursor rules or your assistant's instructions, so it checks before every send:
106
+
107
+ ```text
108
+ Before any marketing email is sent or scheduled, run Okaytosend, the pre-send check for AI-written email: call check_email with the exact email, or POST https://okaytosend.com/api/v1/checks. Pass the pages or files its prices, dates and offers rely on as sources. If the answer is HOLD, stop and show me each problem. Don't rewrite the copy and check again until it passes.
109
+ ```
110
+
111
+ Agents that speak MCP can connect to `https://mcp.okaytosend.com` instead. See [okaytosend.com/docs/connect](https://okaytosend.com/docs/connect).
112
+
113
+ ## Links
114
+
115
+ - Docs: [okaytosend.com/docs](https://okaytosend.com/docs)
116
+ - API reference: [okaytosend.com/docs/api](https://okaytosend.com/docs/api) and [openapi.json](https://okaytosend.com/openapi.json)
117
+ - Support: support@okaytosend.com
@@ -0,0 +1,102 @@
1
+ # okaytosend
2
+
3
+ The pre-send check for AI-written email.
4
+
5
+ Okaytosend checks a marketing email against built-in rules and your own pages and files, then answers HOLD with each problem and the line that proves it, or CLEAR. It finds wrong prices and dates, offers with no end, discount maths that doesn't add up, leftover merge tags and dead links. It never sends or changes an email.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ pip install okaytosend
11
+ ```
12
+
13
+ This installs the `okaytosend` command and the Python client. Python 3.9 or later; no other dependencies. There is also an npm package with the same command: `npx okaytosend`.
14
+
15
+ You need a key: sign up free at [okaytosend.com/sign-up](https://okaytosend.com/sign-up) (25 checks a month, no card), then go to Settings, API keys.
16
+
17
+ ```sh
18
+ export OKAYTOSEND_API_KEY=ots_live_...
19
+ ```
20
+
21
+ ## Check an email
22
+
23
+ ```sh
24
+ okaytosend check launch.eml --source https://bramble.example/pricing
25
+ ```
26
+
27
+ ```text
28
+ HOLD
29
+ 1. CONTRADICTED: “{{first_name}}” · Okaytosend rule: leftover merge tag: ““{{first_name}}” would reach readers as written.”
30
+ 2. CONTRADICTED: “Was £40, now £30: save 40%” · Okaytosend rule: discount maths: “£40 minus £30 gives a saving of 25%.”
31
+ 3. CONTRADICTED: “Bramble Pro costs £9 a month” · Bramble pricing: “Pro: £19 a month”
32
+ Verified 0 · contradicted 3 · conflicting 0 · unverified 0 · N/A 0
33
+ The person decides whether the email or the source is right.
34
+
35
+ Check 3f2a9c1e-f00d-4e02-91fe-b3ed9842716b · https://okaytosend.com/checks/3f2a9c1e-f00d-4e02-91fe-b3ed9842716b
36
+ ```
37
+
38
+ (Bramble is a fictional company.)
39
+
40
+ The email can be an `.eml`, `.html` or `.txt` file, or `-` to read it from stdin. The built-in rules work with no sources at all.
41
+
42
+ | Option | What it does |
43
+ | --- | --- |
44
+ | `--subject`, `--preheader`, `--from-name` | The email's subject, preview text and sender name. An `.eml` file supplies the subject and sender itself |
45
+ | `--project <name or id>` | The project to check against. Optional when the workspace has one project |
46
+ | `--source <url or file>` | A source for this check only: a public URL, or a local `.txt`, `.md`, `.csv`, `.html` or `.json` file. Repeat it, up to 8 |
47
+ | `--revises <check id>` | The check this one follows. Re-checking a HOLD is free |
48
+ | `--fresh` | Read the sources again instead of reusing a result from the last 24 hours |
49
+ | `--detail full` | The full report |
50
+ | `--json` | The API's answer as JSON |
51
+
52
+ Read a saved check with its ID or report link:
53
+
54
+ ```sh
55
+ okaytosend get https://okaytosend.com/checks/3f2a9c1e-f00d-4e02-91fe-b3ed9842716b
56
+ ```
57
+
58
+ ## Exit codes
59
+
60
+ | Code | Meaning |
61
+ | --- | --- |
62
+ | 0 | CLEAR |
63
+ | 1 | HOLD |
64
+ | 2 | Anything else: refused, out of checks, invalid input, network, or still checking after 3 minutes |
65
+
66
+ So an agent or a CI job can stop on a HOLD: `okaytosend check email.html || exit 1`.
67
+
68
+ ## From code
69
+
70
+ ```python
71
+ import os
72
+ from okaytosend import Okaytosend, OkaytosendError
73
+
74
+ okaytosend = Okaytosend(api_key=os.environ["OKAYTOSEND_API_KEY"])
75
+ check = okaytosend.check(
76
+ subject="Spring sale ends Friday",
77
+ html=email_html,
78
+ sources=[{"title": "Pricing", "url": "https://bramble.example/pricing"}],
79
+ )
80
+
81
+ if check.get("verdict") == "HOLD":
82
+ for finding in check["findings"]:
83
+ print(finding["emailQuote"], "→", (finding.get("source") or {}).get("quote"))
84
+ ```
85
+
86
+ `check()` takes the API's request fields as keyword arguments, waits while a check is still running (up to 3 minutes) and raises `OkaytosendError` with the API's code and message when a check is refused. `get_check(id_or_link)` reads a saved check for free.
87
+
88
+ ## Tell your agent
89
+
90
+ Paste this into CLAUDE.md, AGENTS.md, your Cursor rules or your assistant's instructions, so it checks before every send:
91
+
92
+ ```text
93
+ Before any marketing email is sent or scheduled, run Okaytosend, the pre-send check for AI-written email: call check_email with the exact email, or POST https://okaytosend.com/api/v1/checks. Pass the pages or files its prices, dates and offers rely on as sources. If the answer is HOLD, stop and show me each problem. Don't rewrite the copy and check again until it passes.
94
+ ```
95
+
96
+ Agents that speak MCP can connect to `https://mcp.okaytosend.com` instead. See [okaytosend.com/docs/connect](https://okaytosend.com/docs/connect).
97
+
98
+ ## Links
99
+
100
+ - Docs: [okaytosend.com/docs](https://okaytosend.com/docs)
101
+ - API reference: [okaytosend.com/docs/api](https://okaytosend.com/docs/api) and [openapi.json](https://okaytosend.com/openapi.json)
102
+ - Support: support@okaytosend.com
@@ -0,0 +1,28 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "okaytosend"
7
+ version = "0.1.0"
8
+ description = "The pre-send check for AI-written email. Check a marketing email against your own pages and files from the command line or from code."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.9"
13
+ keywords = ["email", "marketing", "verification", "ai-agents", "mcp", "pre-send", "fact-checking", "cli"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Topic :: Communications :: Email",
17
+ ]
18
+ dependencies = []
19
+
20
+ [project.urls]
21
+ Homepage = "https://okaytosend.com"
22
+ Documentation = "https://okaytosend.com/docs"
23
+
24
+ [project.scripts]
25
+ okaytosend = "okaytosend.cli:main"
26
+
27
+ [tool.setuptools.packages.find]
28
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,12 @@
1
+ """okaytosend: the pre-send check for AI-written email. https://okaytosend.com/docs"""
2
+
3
+ from .client import (CHECK_REQUEST_FIELDS, DEFAULT_BASE_URL, MAX_SOURCES, VERSION, Okaytosend, OkaytosendError,
4
+ StillCheckingError, check_id, is_failed, is_pending)
5
+ from .email_file import email_fields, parse_eml
6
+ from .format import format_answer, verdict_line
7
+
8
+ __version__ = VERSION
9
+ __all__ = [
10
+ "Okaytosend", "OkaytosendError", "StillCheckingError", "check_id", "is_failed", "is_pending", "format_answer",
11
+ "verdict_line", "email_fields", "parse_eml", "CHECK_REQUEST_FIELDS", "DEFAULT_BASE_URL", "MAX_SOURCES", "VERSION",
12
+ ]
@@ -0,0 +1,154 @@
1
+ """okaytosend: the pre-send check for AI-written email. Exit codes: 0 CLEAR, 1 HOLD, 2 anything else."""
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+ import sys
7
+ from typing import Callable, List, Optional, TextIO
8
+
9
+ from .client import (MAX_SOURCES, VERSION, Okaytosend, OkaytosendError, StillCheckingError, is_failed)
10
+ from .email_file import email_fields
11
+ from .format import format_answer
12
+
13
+ EXIT_CLEAR, EXIT_HOLD, EXIT_OTHER = 0, 1, 2
14
+ SIGN_UP = ("Get a free key at https://okaytosend.com/sign-up (25 checks a month, no card), "
15
+ "then Settings, API keys, and set OKAYTOSEND_API_KEY.")
16
+ TEXT_SOURCE = (".txt", ".md", ".csv", ".tsv", ".html", ".htm", ".json")
17
+
18
+ DESCRIPTION = """okaytosend %s: the pre-send check for AI-written email
19
+
20
+ Checks a marketing email against built-in rules and your own pages and files,
21
+ and answers HOLD with each problem and its evidence, or CLEAR.""" % VERSION
22
+
23
+ EPILOG = """Exit codes
24
+ 0 CLEAR 1 HOLD 2 anything else (refused, out of checks, invalid input, network)
25
+
26
+ The key is read from OKAYTOSEND_API_KEY. %s
27
+ Docs: https://okaytosend.com/docs""" % SIGN_UP
28
+
29
+
30
+ def _parser() -> argparse.ArgumentParser:
31
+ parser = argparse.ArgumentParser(prog="okaytosend", description=DESCRIPTION, epilog=EPILOG,
32
+ formatter_class=argparse.RawDescriptionHelpFormatter)
33
+ parser.add_argument("-v", "--version", action="version", version=VERSION)
34
+ commands = parser.add_subparsers(dest="command")
35
+ check = commands.add_parser("check", help="Check an email (.eml, .html or .txt; - reads stdin)")
36
+ check.add_argument("file", nargs="?")
37
+ check.add_argument("--subject")
38
+ check.add_argument("--preheader")
39
+ check.add_argument("--from-name", dest="from_name")
40
+ check.add_argument("--project")
41
+ check.add_argument("--source", action="append", default=[],
42
+ help="A public URL or a local .txt, .md, .csv, .html or .json file. Up to %d." % MAX_SOURCES)
43
+ check.add_argument("--revises")
44
+ check.add_argument("--fresh", action="store_true")
45
+ check.add_argument("--detail", choices=["summary", "full"])
46
+ check.add_argument("--json", action="store_true")
47
+ check.add_argument("--base-url", help=argparse.SUPPRESS)
48
+ check.add_argument("--max-wait", type=float, help=argparse.SUPPRESS)
49
+ get = commands.add_parser("get", help="Read a saved check by ID or report link")
50
+ get.add_argument("reference")
51
+ get.add_argument("--json", action="store_true")
52
+ get.add_argument("--base-url", help=argparse.SUPPRESS)
53
+ get.add_argument("--max-wait", type=float, help=argparse.SUPPRESS)
54
+ commands.add_parser("help", help="Show this help")
55
+ return parser
56
+
57
+
58
+ def _source(value: str, read: Callable[[str], str]) -> dict:
59
+ if value.lower().startswith(("http://", "https://")):
60
+ return {"title": value[:240], "url": value}
61
+ name = os.path.basename(value)
62
+ if not value.lower().endswith(TEXT_SOURCE):
63
+ raise OkaytosendError(0, "invalid_input", "%s: only text files can be sent from disk (.txt, .md, .csv, .html, .json). "
64
+ "Pass a public URL for a PDF, Word or Excel file." % name)
65
+ text = read(value)
66
+ if len(text) > 200000:
67
+ raise OkaytosendError(0, "invalid_input", "%s is over 200,000 characters. Pass the relevant section." % name)
68
+ return {"title": name[:240], "text": text}
69
+
70
+
71
+ def _print_error(error: Exception, err: TextIO) -> None:
72
+ if isinstance(error, StillCheckingError):
73
+ url = error.check.get("url")
74
+ print("%s\nCheck %s%s" % (error.message, error.check["id"], " · " + url if url else ""), file=err)
75
+ return
76
+ if isinstance(error, OkaytosendError):
77
+ lines = ["Error (%s): %s" % (error.code, error.message)]
78
+ details = (error.body or {}).get("error") or {}
79
+ for choice in details.get("choices") or []:
80
+ lines.append("- %s (%s)" % (choice["name"], choice["id"]))
81
+ if details.get("billingUrl"):
82
+ lines.append("Billing: " + details["billingUrl"])
83
+ if error.code == "unauthorized":
84
+ lines.append(SIGN_UP)
85
+ print("\n".join(lines), file=err)
86
+ return
87
+ print("Error: %s" % error, file=err)
88
+
89
+
90
+ def _read_file(path: str) -> str:
91
+ with open(path, encoding="utf-8") as handle:
92
+ return handle.read()
93
+
94
+
95
+ def run(argv: List[str], out: TextIO = sys.stdout, err: TextIO = sys.stderr, stdin: TextIO = sys.stdin,
96
+ env: Optional[dict] = None, read: Callable[[str], str] = _read_file,
97
+ sleep: Optional[Callable[[float], None]] = None) -> int:
98
+ env = os.environ if env is None else env
99
+ parser = _parser()
100
+ try:
101
+ args = parser.parse_args(argv)
102
+ except SystemExit as exit_:
103
+ return EXIT_CLEAR if exit_.code == 0 else EXIT_OTHER
104
+ if args.command in (None, "help"):
105
+ parser.print_help(out)
106
+ return EXIT_CLEAR if args.command == "help" else EXIT_OTHER
107
+ try:
108
+ options = {"base_url": args.base_url or env.get("OKAYTOSEND_BASE_URL") or "https://okaytosend.com",
109
+ "user_agent": "okaytosend-cli-python/" + VERSION}
110
+ if args.max_wait is not None:
111
+ options["max_wait_seconds"] = args.max_wait
112
+ if sleep is not None:
113
+ options["sleep"] = sleep
114
+ client = Okaytosend(env.get("OKAYTOSEND_API_KEY") or "", **options)
115
+ if args.command == "get":
116
+ answer = client.get_check(args.reference)
117
+ else:
118
+ if args.file is None:
119
+ if stdin.isatty():
120
+ print("Error (invalid_input): okaytosend check needs a file, or - to read the email from stdin.", file=err)
121
+ return EXIT_OTHER
122
+ args.file = "-"
123
+ content = stdin.read() if args.file == "-" else read(args.file)
124
+ if not content.strip():
125
+ print("Error (invalid_input): the email is empty.", file=err)
126
+ return EXIT_OTHER
127
+ if len(args.source) > MAX_SOURCES:
128
+ print("Error (invalid_input): a check takes at most %d sources; %d were given."
129
+ % (MAX_SOURCES, len(args.source)), file=err)
130
+ return EXIT_OTHER
131
+ request = email_fields("" if args.file == "-" else args.file, content)
132
+ for key in ("subject", "preheader", "from_name", "project", "revises", "detail"):
133
+ if getattr(args, key) is not None:
134
+ request[key] = getattr(args, key)
135
+ if args.fresh:
136
+ request["fresh"] = True
137
+ if args.source:
138
+ request["sources"] = [_source(source, read) for source in args.source]
139
+ answer = client.check(**request)
140
+ print(json.dumps(answer, indent=2, ensure_ascii=False) if args.json else format_answer(answer), file=out)
141
+ if is_failed(answer):
142
+ return EXIT_OTHER
143
+ return EXIT_HOLD if answer.get("verdict") == "HOLD" else EXIT_CLEAR
144
+ except (OkaytosendError, OSError) as error:
145
+ _print_error(error, err)
146
+ return EXIT_OTHER
147
+
148
+
149
+ def main() -> None:
150
+ sys.exit(run(sys.argv[1:]))
151
+
152
+
153
+ if __name__ == "__main__":
154
+ main()
@@ -0,0 +1,136 @@
1
+ """A client for Okaytosend's public API: https://okaytosend.com/openapi.json."""
2
+
3
+ import json
4
+ import re
5
+ import time
6
+ import urllib.error
7
+ import urllib.request
8
+ from typing import Any, Callable, Dict, Optional
9
+
10
+ VERSION = "0.1.0"
11
+ DEFAULT_BASE_URL = "https://okaytosend.com"
12
+ MAX_SOURCES = 8
13
+
14
+ # Every request field, in the OpenAPI document's order.
15
+ CHECK_REQUEST_FIELDS = (
16
+ "project", "kind", "url", "file", "detail", "subject", "preheader", "from_name", "html", "text", "parts",
17
+ "image_urls", "files", "sources", "source", "revises", "fresh", "title",
18
+ )
19
+
20
+ _CHECK_ID = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", re.IGNORECASE)
21
+
22
+
23
+ class OkaytosendError(Exception):
24
+ """An answer the API refused, or a failure to reach it. status is 0 when the API wasn't reached."""
25
+
26
+ def __init__(self, status: int, code: str, message: str, body: Optional[Dict[str, Any]] = None):
27
+ super().__init__(message)
28
+ self.status = status
29
+ self.code = code
30
+ self.message = message
31
+ self.body = body
32
+
33
+
34
+ class StillCheckingError(OkaytosendError):
35
+ """The check was still running when the wait ran out. Read it later with get_check(id)."""
36
+
37
+ def __init__(self, check: Dict[str, Any]):
38
+ super().__init__(202, "checking", "Still checking. Read it later with: okaytosend get " + check["id"])
39
+ self.check = check
40
+
41
+
42
+ def check_id(reference: str) -> str:
43
+ """Accepts a check ID or a report link such as https://okaytosend.com/checks/<id>."""
44
+ match = _CHECK_ID.search(reference.strip())
45
+ if not match:
46
+ raise OkaytosendError(0, "invalid_input", "“%s” is not a check ID or report link." % reference)
47
+ return match.group(0).lower()
48
+
49
+
50
+ def is_failed(answer: Dict[str, Any]) -> bool:
51
+ return answer.get("status") == "failed"
52
+
53
+
54
+ def is_pending(answer: Dict[str, Any]) -> bool:
55
+ return answer.get("status") == "checking"
56
+
57
+
58
+ class Okaytosend:
59
+ def __init__(
60
+ self,
61
+ api_key: str,
62
+ base_url: str = DEFAULT_BASE_URL,
63
+ max_wait_seconds: float = 180,
64
+ user_agent: Optional[str] = None,
65
+ sleep: Callable[[float], None] = time.sleep,
66
+ timeout: float = 120,
67
+ ):
68
+ if not api_key or not api_key.strip():
69
+ raise OkaytosendError(0, "unauthorized",
70
+ "An API key is required: OKAYTOSEND_API_KEY for the command, or api_key in code. "
71
+ "Keys are free at https://okaytosend.com/sign-up.")
72
+ self._api_key = api_key.strip()
73
+ self._base_url = base_url.rstrip("/")
74
+ self._max_wait = max_wait_seconds
75
+ self._user_agent = user_agent or "okaytosend-python/" + VERSION
76
+ self._sleep = sleep
77
+ self._timeout = timeout
78
+
79
+ def check(self, **request: Any) -> Dict[str, Any]:
80
+ """Checks one email. Waits while the check is still running, up to max_wait_seconds."""
81
+ unknown = [name for name in request if name not in CHECK_REQUEST_FIELDS]
82
+ if unknown:
83
+ raise OkaytosendError(0, "invalid_input", "Unknown field %s." % ", ".join(sorted(unknown)))
84
+ sources = request.get("sources") or []
85
+ if len(sources) > MAX_SOURCES:
86
+ raise OkaytosendError(0, "invalid_input",
87
+ "A check takes at most %d sources; %d were given." % (MAX_SOURCES, len(sources)))
88
+ started = time.monotonic()
89
+ body = {name: value for name, value in request.items() if value is not None}
90
+ return self._settle(self._request("POST", "/api/v1/checks", body), started)
91
+
92
+ def get_check(self, reference: str) -> Dict[str, Any]:
93
+ """Reads a saved check by ID or report link. Reading is free."""
94
+ started = time.monotonic()
95
+ return self._settle(self._request("GET", "/api/v1/checks/" + check_id(reference)), started)
96
+
97
+ def _settle(self, answer, started):
98
+ body, retry_after = answer
99
+ while is_pending(body):
100
+ wait = max(1.0, retry_after)
101
+ if time.monotonic() - started + wait > self._max_wait:
102
+ raise StillCheckingError(body)
103
+ self._sleep(wait)
104
+ body, retry_after = self._request("GET", "/api/v1/checks/" + check_id(body["id"]))
105
+ return body
106
+
107
+ def _request(self, method: str, path: str, body: Optional[Dict[str, Any]] = None):
108
+ data = None if body is None else json.dumps(body).encode("utf-8")
109
+ headers = {"Authorization": "Bearer " + self._api_key, "Accept": "application/json", "User-Agent": self._user_agent}
110
+ if data is not None:
111
+ headers["Content-Type"] = "application/json"
112
+ request = urllib.request.Request(self._base_url + path, data=data, method=method, headers=headers)
113
+ try:
114
+ with urllib.request.urlopen(request, timeout=self._timeout) as response:
115
+ status, raw, retry = response.status, response.read(), response.headers.get("Retry-After")
116
+ except urllib.error.HTTPError as error:
117
+ status, raw, retry = error.code, error.read(), error.headers.get("Retry-After")
118
+ except (urllib.error.URLError, OSError) as error:
119
+ reason = getattr(error, "reason", error)
120
+ raise OkaytosendError(0, "network", "Could not reach %s: %s" % (self._base_url, reason)) from None
121
+ try:
122
+ parsed = json.loads(raw.decode("utf-8")) if raw else None
123
+ except ValueError:
124
+ parsed = None
125
+ if status >= 400:
126
+ error_body = (parsed or {}).get("error") if isinstance(parsed, dict) else None
127
+ raise OkaytosendError(status, (error_body or {}).get("code", "unavailable"),
128
+ (error_body or {}).get("message", "The API answered HTTP %d." % status),
129
+ parsed if isinstance(parsed, dict) else None)
130
+ if not isinstance(parsed, dict):
131
+ raise OkaytosendError(status, "unavailable", "The API sent an answer that isn't JSON.")
132
+ try:
133
+ retry_after = float(retry) if retry is not None else 5.0
134
+ except ValueError:
135
+ retry_after = 5.0
136
+ return parsed, retry_after
@@ -0,0 +1,44 @@
1
+ """Turns an email file into the API's fields: .eml through the standard library's email parser,
2
+ .html as html and anything else as text."""
3
+
4
+ import email
5
+ import email.policy
6
+ import re
7
+ from email.header import decode_header, make_header
8
+ from email.utils import parseaddr
9
+ from typing import Dict
10
+
11
+
12
+ def parse_eml(raw: str) -> Dict[str, str]:
13
+ message = email.message_from_string(raw, policy=email.policy.default)
14
+ fields: Dict[str, str] = {}
15
+ subject = message.get("Subject")
16
+ if subject:
17
+ fields["subject"] = str(make_header(decode_header(str(subject))))
18
+ name = parseaddr(str(message.get("From") or ""))[0]
19
+ if name:
20
+ fields["from_name"] = name
21
+ for kind, field in (("html", "html"), ("plain", "text")):
22
+ part = message.get_body(preferencelist=(kind,))
23
+ if part is not None:
24
+ fields[field] = part.get_content().rstrip("\n")
25
+ return fields
26
+
27
+
28
+ def _looks_like_eml(content: str) -> bool:
29
+ head = re.split(r"\r?\n\r?\n", content, maxsplit=1)[0]
30
+ return bool(re.match(r"^(?:[A-Za-z-]+:[^\n]*\r?\n?)+$", head)) and bool(
31
+ re.search(r"^(?:subject|from|mime-version|content-type|to|date):", head, re.IGNORECASE | re.MULTILINE))
32
+
33
+
34
+ def _looks_like_html(content: str) -> bool:
35
+ return bool(re.search(r"<(?:!doctype html|html|body|table|div|p|a|br)\b", content, re.IGNORECASE))
36
+
37
+
38
+ def email_fields(name: str, content: str) -> Dict[str, str]:
39
+ lower = name.lower()
40
+ if lower.endswith(".eml") or (not re.search(r"\.(?:html?|txt|md)$", lower) and _looks_like_eml(content)):
41
+ return parse_eml(content)
42
+ if re.search(r"\.html?$", lower) or (not lower.endswith(".txt") and _looks_like_html(content)):
43
+ return {"html": content}
44
+ return {"text": content}
@@ -0,0 +1,59 @@
1
+ """The text answer: the same lines, in the same order, as the connector's answer and the npm CLI."""
2
+
3
+ import re
4
+ from typing import Any, Dict
5
+
6
+ from .client import is_failed
7
+
8
+
9
+ def excerpt(value: str, limit: int) -> str:
10
+ text = re.sub(r"\s+", " ", value).strip()
11
+ return text if len(text) <= limit else text[: limit - 1] + "…"
12
+
13
+
14
+ def verdict_line(check: Dict[str, Any]) -> str:
15
+ return "CLEAR · draft" if check["verdict"] == "CLEAR" and not check.get("final") else check["verdict"]
16
+
17
+
18
+ def _finding_line(finding: Dict[str, Any]) -> str:
19
+ status = "CONFLICTING" if finding.get("level") == 3 else "CONTRADICTED"
20
+ quote = "“%s”" % excerpt(finding["emailQuote"], 145)
21
+ source = finding.get("source")
22
+ if not source:
23
+ return "%s: %s · %s" % (status, quote, excerpt(finding["title"], 64))
24
+ return "%s: %s · %s: “%s”" % (status, quote, excerpt(source["title"], 64), excerpt(source["quote"], 145))
25
+
26
+
27
+ def format_answer(answer: Dict[str, Any]) -> str:
28
+ if is_failed(answer):
29
+ return "\n".join(["FAILED: " + answer["reason"], "", "Check %s · %s" % (answer["id"], answer["url"])])
30
+ lines = []
31
+ reused = answer.get("reused")
32
+ if reused:
33
+ minutes = reused["minutesAgo"]
34
+ lines.append("The same email was checked %d %s ago with the same sources. This is that answer, and it was free."
35
+ % (minutes, "minute" if minutes == 1 else "minutes"))
36
+ if answer.get("project"):
37
+ lines.append("Project: " + answer["project"]["name"])
38
+ for key in ("provenanceLine", "revisionLine"):
39
+ if answer.get(key):
40
+ lines.append(answer[key])
41
+ lines.append(verdict_line(answer))
42
+ findings = answer.get("findings") or []
43
+ for index, finding in enumerate(findings, start=1):
44
+ lines.append("%d. %s" % (index, _finding_line(finding)))
45
+ unsubscribe = answer.get("unsubscribe") or {}
46
+ if unsubscribe.get("note") and not any(finding.get("rule") == "NO_UNSUBSCRIBE" for finding in findings):
47
+ lines.append(unsubscribe["note"])
48
+ c = answer.get("counts") or {}
49
+ lines.append("Verified %d · contradicted %d · conflicting %d · unverified %d · N/A %d" % (
50
+ c.get("VERIFIED", 0), c.get("CONTRADICTED", 0), c.get("CONFLICTING", 0), c.get("UNVERIFIED", 0), c.get("N/A", 0)))
51
+ if any(finding.get("source") and not finding["source"]["title"].startswith("Okaytosend rule: ")
52
+ and finding.get("rule") != "INTERNAL_MISMATCH" for finding in findings):
53
+ lines.append("The person decides whether the email or the source is right.")
54
+ for step in answer.get("nextSteps") or []:
55
+ lines.append("- " + step)
56
+ if answer.get("draftNote"):
57
+ lines.append(answer["draftNote"])
58
+ lines += ["", "Check %s · %s" % (answer["id"], answer["url"])]
59
+ return "\n".join(lines)
@@ -0,0 +1,117 @@
1
+ Metadata-Version: 2.4
2
+ Name: okaytosend
3
+ Version: 0.1.0
4
+ Summary: The pre-send check for AI-written email. Check a marketing email against your own pages and files from the command line or from code.
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://okaytosend.com
7
+ Project-URL: Documentation, https://okaytosend.com/docs
8
+ Keywords: email,marketing,verification,ai-agents,mcp,pre-send,fact-checking,cli
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Topic :: Communications :: Email
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Dynamic: license-file
15
+
16
+ # okaytosend
17
+
18
+ The pre-send check for AI-written email.
19
+
20
+ Okaytosend checks a marketing email against built-in rules and your own pages and files, then answers HOLD with each problem and the line that proves it, or CLEAR. It finds wrong prices and dates, offers with no end, discount maths that doesn't add up, leftover merge tags and dead links. It never sends or changes an email.
21
+
22
+ ## Install
23
+
24
+ ```sh
25
+ pip install okaytosend
26
+ ```
27
+
28
+ This installs the `okaytosend` command and the Python client. Python 3.9 or later; no other dependencies. There is also an npm package with the same command: `npx okaytosend`.
29
+
30
+ You need a key: sign up free at [okaytosend.com/sign-up](https://okaytosend.com/sign-up) (25 checks a month, no card), then go to Settings, API keys.
31
+
32
+ ```sh
33
+ export OKAYTOSEND_API_KEY=ots_live_...
34
+ ```
35
+
36
+ ## Check an email
37
+
38
+ ```sh
39
+ okaytosend check launch.eml --source https://bramble.example/pricing
40
+ ```
41
+
42
+ ```text
43
+ HOLD
44
+ 1. CONTRADICTED: “{{first_name}}” · Okaytosend rule: leftover merge tag: ““{{first_name}}” would reach readers as written.”
45
+ 2. CONTRADICTED: “Was £40, now £30: save 40%” · Okaytosend rule: discount maths: “£40 minus £30 gives a saving of 25%.”
46
+ 3. CONTRADICTED: “Bramble Pro costs £9 a month” · Bramble pricing: “Pro: £19 a month”
47
+ Verified 0 · contradicted 3 · conflicting 0 · unverified 0 · N/A 0
48
+ The person decides whether the email or the source is right.
49
+
50
+ Check 3f2a9c1e-f00d-4e02-91fe-b3ed9842716b · https://okaytosend.com/checks/3f2a9c1e-f00d-4e02-91fe-b3ed9842716b
51
+ ```
52
+
53
+ (Bramble is a fictional company.)
54
+
55
+ The email can be an `.eml`, `.html` or `.txt` file, or `-` to read it from stdin. The built-in rules work with no sources at all.
56
+
57
+ | Option | What it does |
58
+ | --- | --- |
59
+ | `--subject`, `--preheader`, `--from-name` | The email's subject, preview text and sender name. An `.eml` file supplies the subject and sender itself |
60
+ | `--project <name or id>` | The project to check against. Optional when the workspace has one project |
61
+ | `--source <url or file>` | A source for this check only: a public URL, or a local `.txt`, `.md`, `.csv`, `.html` or `.json` file. Repeat it, up to 8 |
62
+ | `--revises <check id>` | The check this one follows. Re-checking a HOLD is free |
63
+ | `--fresh` | Read the sources again instead of reusing a result from the last 24 hours |
64
+ | `--detail full` | The full report |
65
+ | `--json` | The API's answer as JSON |
66
+
67
+ Read a saved check with its ID or report link:
68
+
69
+ ```sh
70
+ okaytosend get https://okaytosend.com/checks/3f2a9c1e-f00d-4e02-91fe-b3ed9842716b
71
+ ```
72
+
73
+ ## Exit codes
74
+
75
+ | Code | Meaning |
76
+ | --- | --- |
77
+ | 0 | CLEAR |
78
+ | 1 | HOLD |
79
+ | 2 | Anything else: refused, out of checks, invalid input, network, or still checking after 3 minutes |
80
+
81
+ So an agent or a CI job can stop on a HOLD: `okaytosend check email.html || exit 1`.
82
+
83
+ ## From code
84
+
85
+ ```python
86
+ import os
87
+ from okaytosend import Okaytosend, OkaytosendError
88
+
89
+ okaytosend = Okaytosend(api_key=os.environ["OKAYTOSEND_API_KEY"])
90
+ check = okaytosend.check(
91
+ subject="Spring sale ends Friday",
92
+ html=email_html,
93
+ sources=[{"title": "Pricing", "url": "https://bramble.example/pricing"}],
94
+ )
95
+
96
+ if check.get("verdict") == "HOLD":
97
+ for finding in check["findings"]:
98
+ print(finding["emailQuote"], "→", (finding.get("source") or {}).get("quote"))
99
+ ```
100
+
101
+ `check()` takes the API's request fields as keyword arguments, waits while a check is still running (up to 3 minutes) and raises `OkaytosendError` with the API's code and message when a check is refused. `get_check(id_or_link)` reads a saved check for free.
102
+
103
+ ## Tell your agent
104
+
105
+ Paste this into CLAUDE.md, AGENTS.md, your Cursor rules or your assistant's instructions, so it checks before every send:
106
+
107
+ ```text
108
+ Before any marketing email is sent or scheduled, run Okaytosend, the pre-send check for AI-written email: call check_email with the exact email, or POST https://okaytosend.com/api/v1/checks. Pass the pages or files its prices, dates and offers rely on as sources. If the answer is HOLD, stop and show me each problem. Don't rewrite the copy and check again until it passes.
109
+ ```
110
+
111
+ Agents that speak MCP can connect to `https://mcp.okaytosend.com` instead. See [okaytosend.com/docs/connect](https://okaytosend.com/docs/connect).
112
+
113
+ ## Links
114
+
115
+ - Docs: [okaytosend.com/docs](https://okaytosend.com/docs)
116
+ - API reference: [okaytosend.com/docs/api](https://okaytosend.com/docs/api) and [openapi.json](https://okaytosend.com/openapi.json)
117
+ - Support: support@okaytosend.com
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/okaytosend/__init__.py
5
+ src/okaytosend/cli.py
6
+ src/okaytosend/client.py
7
+ src/okaytosend/email_file.py
8
+ src/okaytosend/format.py
9
+ src/okaytosend.egg-info/PKG-INFO
10
+ src/okaytosend.egg-info/SOURCES.txt
11
+ src/okaytosend.egg-info/dependency_links.txt
12
+ src/okaytosend.egg-info/entry_points.txt
13
+ src/okaytosend.egg-info/top_level.txt
14
+ tests/test_okaytosend.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ okaytosend = okaytosend.cli:main
@@ -0,0 +1 @@
1
+ okaytosend
@@ -0,0 +1,291 @@
1
+ """Run with: python3 -m unittest discover -s tests (from sdk/python, with src on the path)."""
2
+
3
+ import io
4
+ import json
5
+ import re
6
+ import sys
7
+ import threading
8
+ import unittest
9
+ from http.server import BaseHTTPRequestHandler, HTTPServer
10
+ from pathlib import Path
11
+
12
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
13
+
14
+ from okaytosend import CHECK_REQUEST_FIELDS, check_id, email_fields, parse_eml # noqa: E402
15
+ from okaytosend.cli import EXIT_CLEAR, EXIT_HOLD, EXIT_OTHER, run # noqa: E402
16
+
17
+ ID = "3f2a9c1e-f00d-4e02-91fe-b3ed9842716b"
18
+ KEY = "ots_live_fictional_key_for_tests"
19
+
20
+
21
+ def url_of(check):
22
+ return "https://okaytosend.com/checks/" + check
23
+
24
+
25
+ HOLD = {
26
+ "id": ID, "url": url_of(ID), "verdict": "HOLD", "final": False,
27
+ "counts": {"VERIFIED": 0, "CONTRADICTED": 3, "CONFLICTING": 0, "UNVERIFIED": 0, "N/A": 0}, "findingCount": 3,
28
+ "findings": [
29
+ {"title": "Leftover merge tag", "rule": "PLACEHOLDER_LEFT", "state": "open", "level": 2, "emailQuote": "{{first_name}}",
30
+ "source": {"title": "Okaytosend rule: leftover merge tag", "quote": "“{{first_name}}” would reach readers as written."}},
31
+ {"title": "Discount maths", "rule": "DISCOUNT_MATH", "state": "open", "level": 2, "emailQuote": "Was £40, now £30: save 40%",
32
+ "source": {"title": "Okaytosend rule: discount maths", "quote": "£40 minus £30 gives a saving of 25%."}},
33
+ {"title": "Claim contradicted", "rule": "VALUE_MISMATCH", "state": "open", "level": 2,
34
+ "emailQuote": "Bramble Pro costs £9 a month",
35
+ "source": {"title": "Bramble pricing", "quote": "Pro: £19 a month", "url": "https://bramble.example/pricing"}},
36
+ ],
37
+ "nextSteps": ["If the copy is wrong: change it where it's published, then I'll check it again as it is there."],
38
+ "draftNote": "This was a draft. For the final check, send a real test to bramble@check.okaytosend.com.",
39
+ }
40
+ CLEAR = dict(HOLD, verdict="CLEAR", counts={"VERIFIED": 2, "CONTRADICTED": 0, "CONFLICTING": 0, "UNVERIFIED": 0, "N/A": 0},
41
+ findingCount=0, findings=[], nextSteps=[])
42
+
43
+ # The npm CLI's test asserts these exact lines too, so both packages print the same answer.
44
+ HOLD_TEXT = "\n".join([
45
+ "HOLD",
46
+ "1. CONTRADICTED: “{{first_name}}” · Okaytosend rule: leftover merge tag: ““{{first_name}}” would reach readers as written.”",
47
+ "2. CONTRADICTED: “Was £40, now £30: save 40%” · Okaytosend rule: discount maths: “£40 minus £30 gives a saving of 25%.”",
48
+ "3. CONTRADICTED: “Bramble Pro costs £9 a month” · Bramble pricing: “Pro: £19 a month”",
49
+ "Verified 0 · contradicted 3 · conflicting 0 · unverified 0 · N/A 0",
50
+ "The person decides whether the email or the source is right.",
51
+ "- If the copy is wrong: change it where it's published, then I'll check it again as it is there.",
52
+ "This was a draft. For the final check, send a real test to bramble@check.okaytosend.com.",
53
+ "",
54
+ "Check %s · %s" % (ID, url_of(ID)),
55
+ ])
56
+
57
+
58
+ class FakeApi:
59
+ def __init__(self):
60
+ self.replies = []
61
+ self.seen = []
62
+ api = self
63
+
64
+ class Handler(BaseHTTPRequestHandler):
65
+ def _answer(self):
66
+ length = int(self.headers.get("Content-Length") or 0)
67
+ raw = self.rfile.read(length) if length else b""
68
+ api.seen.append({"method": self.command, "path": self.path, "auth": self.headers.get("Authorization"),
69
+ "agent": self.headers.get("User-Agent"), "body": json.loads(raw) if raw else None})
70
+ status, body, headers = api.replies.pop(0) if api.replies else (500, {"error": {"code": "unavailable", "message": "No reply queued."}}, {})
71
+ payload = json.dumps(body).encode("utf-8")
72
+ self.send_response(status)
73
+ self.send_header("Content-Type", "application/json")
74
+ self.send_header("Content-Length", str(len(payload)))
75
+ for name, value in headers.items():
76
+ self.send_header(name, value)
77
+ self.end_headers()
78
+ self.wfile.write(payload)
79
+
80
+ do_GET = _answer
81
+ do_POST = _answer
82
+
83
+ def log_message(self, *args):
84
+ pass
85
+
86
+ self.server = HTTPServer(("127.0.0.1", 0), Handler)
87
+ self.base = "http://127.0.0.1:%d" % self.server.server_address[1]
88
+ threading.Thread(target=self.server.serve_forever, daemon=True).start()
89
+
90
+ def close(self):
91
+ self.server.shutdown()
92
+ self.server.server_close()
93
+
94
+
95
+ class Tty(io.StringIO):
96
+ def isatty(self):
97
+ return True
98
+
99
+
100
+ class CliTest(unittest.TestCase):
101
+ @classmethod
102
+ def setUpClass(cls):
103
+ cls.api = FakeApi()
104
+
105
+ @classmethod
106
+ def tearDownClass(cls):
107
+ cls.api.close()
108
+
109
+ def setUp(self):
110
+ self.api.replies = []
111
+ self.api.seen = []
112
+ self.files = {"launch.txt": "Hello {{first_name}}.\nWas £40, now £30: save 40%. Bramble Pro costs £9 a month."}
113
+ self.sleeps = []
114
+
115
+ def cli(self, *argv, key=KEY, stdin=None, base=None):
116
+ out, err = io.StringIO(), io.StringIO()
117
+
118
+ def read(path):
119
+ if path not in self.files:
120
+ raise FileNotFoundError(2, "No such file", path)
121
+ return self.files[path]
122
+
123
+ env = {"OKAYTOSEND_BASE_URL": base or self.api.base}
124
+ if key is not None:
125
+ env["OKAYTOSEND_API_KEY"] = key
126
+ code = run(list(argv), out=out, err=err, stdin=stdin if stdin is not None else Tty(""), env=env, read=read,
127
+ sleep=self.sleeps.append)
128
+ return code, out.getvalue().rstrip("\n"), err.getvalue().rstrip("\n")
129
+
130
+ def test_clear_exits_0_with_the_check_line(self):
131
+ self.api.replies = [(201, CLEAR, {})]
132
+ code, out, _ = self.cli("check", "launch.txt", "--subject", "Spring")
133
+ self.assertEqual(code, EXIT_CLEAR)
134
+ self.assertEqual(out.split("\n")[0], "CLEAR · draft")
135
+ self.assertEqual(out.split("\n")[-1], "Check %s · %s" % (ID, url_of(ID)))
136
+ seen = self.api.seen[0]
137
+ self.assertEqual((seen["method"], seen["path"], seen["auth"]), ("POST", "/api/v1/checks", "Bearer " + KEY))
138
+ self.assertEqual(seen["body"], {"subject": "Spring", "text": self.files["launch.txt"]})
139
+ self.assertRegex(seen["agent"], r"^okaytosend-cli-python/\d+\.\d+\.\d+$")
140
+
141
+ def test_hold_exits_1_and_prints_the_same_lines_as_the_connector(self):
142
+ self.api.replies = [(201, HOLD, {})]
143
+ code, out, _ = self.cli("check", "launch.txt")
144
+ self.assertEqual(code, EXIT_HOLD)
145
+ self.assertEqual(out, HOLD_TEXT)
146
+
147
+ def test_json_prints_the_api_answer(self):
148
+ self.api.replies = [(201, HOLD, {})]
149
+ code, out, _ = self.cli("check", "launch.txt", "--json")
150
+ self.assertEqual(code, EXIT_HOLD)
151
+ self.assertEqual(json.loads(out), HOLD)
152
+
153
+ def test_refusals_exit_2_with_the_api_message(self):
154
+ cases = [
155
+ (402, {"code": "cap_reached", "message": "This workspace reached its overage cap. Nothing was checked.",
156
+ "billingUrl": "https://okaytosend.com/billing"}, "Billing: https://okaytosend.com/billing"),
157
+ (401, {"code": "unauthorized", "message": "Missing or invalid key."}, "okaytosend.com/sign-up"),
158
+ (400, {"code": "project_required", "message": "Choose a project.",
159
+ "choices": [{"id": "p1", "name": "Bramble"}, {"id": "p2", "name": "Willowlight"}]}, "- Willowlight (p2)"),
160
+ ]
161
+ for status, error, shown in cases:
162
+ with self.subTest(status=status):
163
+ self.api.replies = [(status, {"error": error}, {})]
164
+ code, _, err = self.cli("check", "launch.txt")
165
+ self.assertEqual(code, EXIT_OTHER)
166
+ self.assertIn("Error (%s): %s" % (error["code"], error["message"]), err)
167
+ self.assertIn(shown, err)
168
+ self.assertNotIn(KEY, err)
169
+
170
+ def test_network_failure_exits_2(self):
171
+ code, _, err = self.cli("check", "launch.txt", base="http://127.0.0.1:1")
172
+ self.assertEqual(code, EXIT_OTHER)
173
+ self.assertTrue(err.startswith("Error (network): Could not reach http://127.0.0.1:1"), err)
174
+
175
+ def test_failed_check_exits_2(self):
176
+ self.api.replies = [(200, {"id": ID, "url": url_of(ID), "status": "failed", "reason": "A source could not be read."}, {})]
177
+ code, out, _ = self.cli("check", "launch.txt")
178
+ self.assertEqual(code, EXIT_OTHER)
179
+ self.assertEqual(out, "FAILED: A source could not be read.\n\nCheck %s · %s" % (ID, url_of(ID)))
180
+
181
+ def test_waits_through_202_with_retry_after(self):
182
+ pending = {"id": ID, "url": url_of(ID), "status": "checking"}
183
+ self.api.replies = [(202, pending, {"Retry-After": "4"}), (202, pending, {"Retry-After": "4"}), (200, HOLD, {})]
184
+ code, out, _ = self.cli("check", "launch.txt")
185
+ self.assertEqual(code, EXIT_HOLD)
186
+ self.assertEqual(self.sleeps, [4.0, 4.0])
187
+ self.assertEqual([s["method"] + " " + s["path"] for s in self.api.seen],
188
+ ["POST /api/v1/checks", "GET /api/v1/checks/" + ID, "GET /api/v1/checks/" + ID])
189
+
190
+ def test_gives_up_past_the_wait(self):
191
+ self.api.replies = [(202, {"id": ID, "url": url_of(ID), "status": "checking"}, {"Retry-After": "5"})]
192
+ code, _, err = self.cli("check", "launch.txt", "--max-wait", "3")
193
+ self.assertEqual(code, EXIT_OTHER)
194
+ self.assertIn("okaytosend get " + ID, err)
195
+ self.assertIn("Check %s · %s" % (ID, url_of(ID)), err)
196
+
197
+ def test_up_to_8_sources_and_a_ninth_is_refused_before_any_request(self):
198
+ self.files["rates.md"] = "Pro: £19 a month"
199
+ eight = ["https://bramble.example/pricing", "rates.md"] + ["https://bramble.example/%d" % i for i in range(6)]
200
+ self.api.replies = [(201, CLEAR, {})]
201
+ args = [part for source in eight for part in ("--source", source)]
202
+ self.assertEqual(self.cli("check", "launch.txt", *args)[0], EXIT_CLEAR)
203
+ sources = self.api.seen[0]["body"]["sources"]
204
+ self.assertEqual(len(sources), 8)
205
+ self.assertEqual(sources[:2], [{"title": "https://bramble.example/pricing", "url": "https://bramble.example/pricing"},
206
+ {"title": "rates.md", "text": "Pro: £19 a month"}])
207
+ self.api.seen = []
208
+ code, _, err = self.cli("check", "launch.txt", *(args + ["--source", "https://bramble.example/9"]))
209
+ self.assertEqual(code, EXIT_OTHER)
210
+ self.assertIn("at most 8 sources; 9 were given", err)
211
+ self.assertEqual(self.api.seen, [])
212
+
213
+ def test_local_pdf_source_is_refused(self):
214
+ code, _, err = self.cli("check", "launch.txt", "--source", "terms.pdf")
215
+ self.assertEqual(code, EXIT_OTHER)
216
+ self.assertIn("Pass a public URL for a PDF, Word or Excel file.", err)
217
+ self.assertEqual(self.api.seen, [])
218
+
219
+ def test_missing_key_sends_nothing(self):
220
+ code, _, err = self.cli("check", "launch.txt", key=None)
221
+ self.assertEqual(code, EXIT_OTHER)
222
+ self.assertIn("https://okaytosend.com/sign-up", err)
223
+ self.assertEqual(self.api.seen, [])
224
+
225
+ def test_reads_stdin(self):
226
+ self.api.replies = [(201, CLEAR, {})]
227
+ code, _, _ = self.cli("check", "-", stdin=io.StringIO("<p>Hello <b>there</b></p>"))
228
+ self.assertEqual(code, EXIT_CLEAR)
229
+ self.assertEqual(self.api.seen[0]["body"], {"html": "<p>Hello <b>there</b></p>"})
230
+
231
+ def test_get_by_report_link(self):
232
+ self.api.replies = [(200, HOLD, {})]
233
+ code, out, _ = self.cli("get", url_of(ID))
234
+ self.assertEqual(code, EXIT_HOLD)
235
+ self.assertEqual(self.api.seen[0]["path"], "/api/v1/checks/" + ID)
236
+ self.assertEqual(out.split("\n")[-1], "Check %s · %s" % (ID, url_of(ID)))
237
+
238
+ def test_help_leads_with_the_phrase(self):
239
+ code, out, _ = self.cli("help")
240
+ self.assertEqual(code, EXIT_CLEAR)
241
+ self.assertIn("the pre-send check for AI-written email", out)
242
+ self.assertIn("0 CLEAR 1 HOLD 2 anything else", out)
243
+
244
+
245
+ class EmailFileTest(unittest.TestCase):
246
+ def test_multipart_eml(self):
247
+ import base64
248
+ eml = "\r\n".join([
249
+ 'From: "Bramble Team" <hello@bramble.example>',
250
+ "Subject: =?UTF-8?B?U3ByaW5nIHNhbGUg4oCUIGVuZHMgRnJpZGF5?=",
251
+ "MIME-Version: 1.0",
252
+ 'Content-Type: multipart/alternative; boundary="b1"',
253
+ "",
254
+ "--b1",
255
+ "Content-Type: text/plain; charset=utf-8",
256
+ "Content-Transfer-Encoding: quoted-printable",
257
+ "",
258
+ "Save 20% =E2=80=94 ends Friday.=",
259
+ "",
260
+ "--b1",
261
+ "Content-Type: text/html; charset=utf-8",
262
+ "Content-Transfer-Encoding: base64",
263
+ "",
264
+ base64.b64encode("<p>Save 20% — ends Friday.</p>".encode("utf-8")).decode("ascii"),
265
+ "--b1--",
266
+ "",
267
+ ])
268
+ self.assertEqual(parse_eml(eml), {"subject": "Spring sale — ends Friday", "from_name": "Bramble Team",
269
+ "text": "Save 20% — ends Friday.", "html": "<p>Save 20% — ends Friday.</p>"})
270
+
271
+ def test_html_and_text_files(self):
272
+ self.assertEqual(email_fields("a.html", "Hi"), {"html": "Hi"})
273
+ self.assertEqual(email_fields("a.txt", "<p>Hi</p>"), {"text": "<p>Hi</p>"})
274
+
275
+ def test_check_reference(self):
276
+ self.assertEqual(check_id(url_of(ID.upper())), ID)
277
+ with self.assertRaises(Exception):
278
+ check_id("yesterday's check")
279
+
280
+
281
+ class DriftTest(unittest.TestCase):
282
+ def test_request_fields_match_the_npm_package(self):
283
+ # The npm package's test compares its list with the OpenAPI document, so this chain keeps all three in step.
284
+ source = (Path(__file__).resolve().parents[3] / "packages/cli/src/types.ts").read_text(encoding="utf-8")
285
+ block = source[source.index("export const CHECK_REQUEST_FIELDS = ["):]
286
+ block = block[: block.index("] as const")]
287
+ self.assertEqual(re.findall(r'"([a-z_]+)"', block), list(CHECK_REQUEST_FIELDS))
288
+
289
+
290
+ if __name__ == "__main__":
291
+ unittest.main()