diff --git a/.github/scripts/check_strict_types.sh b/.github/scripts/check_strict_types.sh index 7b46c0af0..170f9ec6d 100755 --- a/.github/scripts/check_strict_types.sh +++ b/.github/scripts/check_strict_types.sh @@ -15,6 +15,7 @@ import atexit import posthog from posthog import FeatureFlagEvaluations, FlagValue, Posthog +from posthog.emails import AsyncEmails, Emails, SendEmailResult from posthog.ai.evaluations import ( AsyncOfflineEvaluations, BooleanScorerConfig, @@ -40,6 +41,18 @@ span.end() _ = (flag_value, all_flags, enabled, payload, evaluations, active) +emails = Emails("phs_example") +template_send: SendEmailResult = emails.send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", template_data={"name": "Ada"}) +rendered_send: SendEmailResult = emails.send(to="user@example.com", template_key="password-reset", subject="Reset", html="

Reset

", from_="Acme ", reply_to=["help@example.com"]) +local_template_send: SendEmailResult = emails.send(to="user@example.com", template_key="welcome", subject="Hi {{ variables.name }}", text="Hi", template_data={"name": "Ada"}) +invite_send: SendEmailResult = emails.send(to="user@example.com", template_key="invite", subject="Invite", html="

Invite

", cc="team@example.com", bcc=["audit@example.com"], headers={"X-Entity-Ref-ID": "order-123"}, tags=[{"name": "category", "value": "invite"}], attachments=[{"filename": "invite.ics", "content": b"BEGIN:VCALENDAR", "content_type": "text/calendar"}, {"filename": "logo.png", "content": "iVBORw0KGgo=", "content_id": "logo"}]) +_ = (template_send, rendered_send, local_template_send, invite_send) + + +async def async_email_types() -> None: + sent: SendEmailResult = await AsyncEmails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="

Hi

") + _ = sent + async def offline_evaluation_types( sync_client: OfflineEvaluations, async_client: AsyncOfflineEvaluations @@ -64,15 +77,24 @@ async def offline_evaluation_types( _ = config PY -cat > "$tmp/invalid_offline_types.py" <<'PY' +cat > "$tmp/invalid_types.py" <<'PY' # pyright: strict from posthog.ai.evaluations import BooleanScorerConfig, CategoricalScorerConfig, NumericPassingRule, NumericScorerConfig, OfflineEvaluations +from posthog.emails import AsyncEmails, Emails client = OfflineEvaluations(project_id=123, secret_key="phx_example") NumericPassingRule(operator="gt", threshold=0.8) # expected-type-error NumericScorerConfig(unknown_setting=True) # expected-type-error CategoricalScorerConfig(selection_mode="single") # expected-type-error client.scorers.create(name="Bad config", kind="numeric", config=BooleanScorerConfig(true_is_failure=True)) # expected-type-error +Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", template_key="welcome", subject="Hi", html="

Hi

") # expected-type-error +Emails("phs_example").send(to="user@example.com", template_key="welcome", html="

Hi

") # expected-type-error +Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", cc="team@example.com") # expected-type-error +Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="

Hi

", attachments=[{"filename": "a.txt", "content": [104, 105]}]) # expected-type-error + + +async def invalid_async_email() -> None: + await AsyncEmails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", subject="Hi") # expected-type-error PY "$tmp/.venv/bin/python" - <<'PY' > "$tmp/public_api_access.py" @@ -116,8 +138,8 @@ JSON cd "$tmp" "$tmp/.venv/bin/python" -m pyright strict_posthog_types.py public_api_access.py -if "$tmp/.venv/bin/python" -m pyright --outputjson invalid_offline_types.py > invalid_types.json; then - echo "Invalid offline evaluation configurations unexpectedly passed type checking." +if "$tmp/.venv/bin/python" -m pyright --outputjson invalid_types.py > invalid_types.json; then + echo "Invalid offline evaluation configurations and email sends unexpectedly passed type checking." exit 1 fi "$tmp/.venv/bin/python" - <<'PY' @@ -125,11 +147,11 @@ import json from pathlib import Path expected = { - index for index, line in enumerate(Path("invalid_offline_types.py").read_text().splitlines()) + index for index, line in enumerate(Path("invalid_types.py").read_text().splitlines()) if "expected-type-error" in line } diagnostics = json.loads(Path("invalid_types.json").read_text())["generalDiagnostics"] actual = {item["range"]["start"]["line"] for item in diagnostics if item["severity"] == "error"} assert actual == expected, diagnostics -print("Offline evaluation configuration types reject invalid inputs.") +print("Offline evaluation configuration and email send types reject invalid inputs.") PY diff --git a/.sampo/changesets/emails-code-form.md b/.sampo/changesets/emails-code-form.md new file mode 100644 index 000000000..7a2051647 --- /dev/null +++ b/.sampo/changesets/emails-code-form.md @@ -0,0 +1,7 @@ +--- +pypi/posthog: minor +--- + +Send transactional email from content in your code with `posthog.emails.send(template_key=..., subject=..., html=...)`. Without `template_data`, the content is sent as is. With `template_data`, the content is a template: PostHog fills in its variables, and the client uploads it by key whenever PostHog doesn't hold its content yet, then sends again with the same idempotency key. A send that mixes `template_id` and `template_key` fails type checks and raises `TypeError`. + +A code send also takes `cc`, `bcc`, `headers`, `tags` and `attachments`. An attachment's `content` can be `bytes`, `bytearray` or `memoryview`, which the client encodes as Base64, or a Base64 string. diff --git a/posthog/async_client.py b/posthog/async_client.py index 74f2d1533..7a1f62269 100644 --- a/posthog/async_client.py +++ b/posthog/async_client.py @@ -260,7 +260,7 @@ def __init__( @property def emails(self) -> AsyncEmails: """ - Send transactional email from PostHog email templates. + Send transactional email from PostHog email templates or from content in your code. Needs ``secret_key``, a project secret API key with the ``hog_flow:write`` scope, and ``posthog[async]``. Sends go to ``app_host``, or to the PostHog diff --git a/posthog/client.py b/posthog/client.py index fc1368256..1eb1207ac 100644 --- a/posthog/client.py +++ b/posthog/client.py @@ -1152,7 +1152,7 @@ def _request_identity_kwargs(self) -> Dict[str, str]: @property def emails(self) -> Emails: """ - Send transactional email from PostHog email templates. + Send transactional email from PostHog email templates or from content in your code. Needs ``secret_key``, a project secret API key with the ``hog_flow:write`` scope. Sends go to ``app_host``, or to the PostHog Cloud app host of diff --git a/posthog/emails.py b/posthog/emails.py index d6d66560a..69ff9f79e 100644 --- a/posthog/emails.py +++ b/posthog/emails.py @@ -1,4 +1,4 @@ -"""Transactional email, sent from an email template in PostHog. +"""Transactional email, sent from an email template in PostHog or from content in your code. Setup: @@ -22,6 +22,26 @@ idempotency_key="welcome:user_123", ) print(result.id) # the queued email + +# Content you rendered for this recipient, named by a key +posthog.emails.send( + to="user@example.com", + template_key="password-reset", + subject="Reset your password", + html=rendered_html, + distinct_id="user_123", +) + +# A template in your code. PostHog fills in the variables, and the client +# uploads the template whenever its content changes. +posthog.emails.send( + to="user@example.com", + template_key="welcome", + subject="Welcome, {{ variables.name }}", + html=welcome_html, + template_data={"name": "Ada"}, + distinct_id="user_123", +) ``` ``posthog.emails`` above is the client's property. For async code, use @@ -67,6 +87,8 @@ from __future__ import annotations import asyncio +import base64 +import hashlib import importlib import json import logging @@ -77,10 +99,21 @@ import time from dataclasses import dataclass from types import TracebackType -from typing import Any, Callable, Mapping, Optional, TypeVar, Union +from typing import ( + Any, + Callable, + Mapping, + Optional, + Sequence, + TypedDict, + TypeVar, + Union, + overload, +) from uuid import UUID, uuid4 import requests +from typing_extensions import NotRequired, Unpack from .capture_v1 import _parse_retry_after from .request import ( @@ -92,11 +125,25 @@ from .utils import clean from .version import VERSION -__all__ = ["AsyncEmails", "EmailError", "EmailWarning", "Emails", "SendEmailResult"] +__all__ = [ + "AsyncEmails", + "CodeEmailArgs", + "EmailAttachment", + "EmailError", + "EmailTag", + "EmailWarning", + "Emails", + "SendEmailResult", + "TemplateEmailArgs", +] log = logging.getLogger("posthog") _SEND_PATH = "/api/projects/@current/messaging_templates/{template_id}/send/" +_CODE_SEND_PATH = "/api/projects/@current/messaging/send/email/" +_UPLOAD_PATH = "/api/projects/@current/messaging_templates/by_key/{template_key}/" +_TEMPLATE_KEY = re.compile(r"[a-zA-Z0-9_-]{1,400}") +_CONTENT_HASH_HEADER = b"posthog-email-template-v1\n" _MAX_RETRY_DELAY = 30.0 _IDEMPOTENCY_KEY = re.compile(r"^[\x21-\x7e]{1,255}$") _IN_FLIGHT_CODES = frozenset({"idempotency_key_in_flight"}) @@ -152,11 +199,318 @@ class SendEmailResult: warnings: tuple[EmailWarning, ...] = () +class EmailTag(TypedDict): + """A name and value that PostHog adds to the email's engagement events as ``$email_tags``.""" + + name: str + value: str + + +class EmailAttachment(TypedDict): + """A file sent with the email. + + Args: + filename: The file name the recipient sees, such as ``invite.ics``. + content: The file as ``bytes``, ``bytearray`` or ``memoryview``, or + already Base64 encoded as a string. + content_type: The MIME type. Without it, the type follows the file name. + content_id: Shows the file inline: reference it in ``html`` as + ```` with ``content_id`` ``logo``. + """ + + filename: str + content: Union[bytes, bytearray, memoryview, str] + content_type: NotRequired[str] + content_id: NotRequired[str] + + +class _RecipientArgs(TypedDict): + to: str + distinct_id: NotRequired[Optional[str]] + idempotency_key: NotRequired[Optional[str]] + + +class TemplateEmailArgs(_RecipientArgs): + """A send of an email template made in PostHog, named by its ID. + + Args: + to: One recipient email address. + template_id: The UUID of a template made transactional in PostHog. + template_data: Values for the template's ``{{ variables.* }}`` + placeholders. + distinct_id: The recipient's distinct ID in your product. + idempotency_key: 1 to 255 visible ASCII characters. + """ + + template_id: Union[str, UUID] + template_data: NotRequired[Optional[Mapping[str, Any]]] + + +class CodeEmailArgs(_RecipientArgs): + """A send of email content that lives in your code, named by a key. + + Without ``template_data``, the content is rendered for this one recipient + and sent as is. With it, the content is a template: PostHog fills in its + ``{{ variables.* }}`` placeholders, and the client uploads the template + whenever PostHog doesn't hold its content yet. + + A PostHog version that doesn't take a field yet, such as ``cc``, refuses + the send with ``invalid_request`` and names the field in + ``EmailError.field``. It never drops the field and sends the rest. + + Args: + to: One recipient email address. + template_key: Names the email, so its metrics, logs and status group + under it. Letters, digits, ``-`` and ``_``, at most 400. + subject: The subject line. + html: The HTML body. Give ``html``, ``text`` or both. + text: The plain-text body. Without it, PostHog derives it from + ``html``. HTML with no text in it, such as a single image, goes out + without a plain-text part. + from_: A verified sender, such as ``"Acme "``. + reply_to: One address or a list of addresses. + cc: One address or a list of addresses that get a visible copy. + bcc: One address or a list of addresses that get a hidden copy. + headers: Extra email headers by name, such as ``X-Entity-Ref-ID``. + tags: Names and values that PostHog adds to the email's engagement + events. + attachments: Files sent with the email. + capture_engagement: Capture opens and clicks. Without it, PostHog's + default applies, which is on. + template_data: Values for the ``{{ variables.* }}`` placeholders. + distinct_id: The recipient's distinct ID in your product. + idempotency_key: 1 to 255 visible ASCII characters. Template sends + and code sends share one set of keys: a key already used for + another email, or for a ``template_id`` send, raises + ``idempotency_key_reused``. A retry with the same key returns the + first send's result, also when its workflow was paused since. + """ + + template_key: str + subject: str + html: NotRequired[str] + text: NotRequired[str] + from_: NotRequired[str] + reply_to: NotRequired[Union[str, Sequence[str]]] + cc: NotRequired[Union[str, Sequence[str]]] + bcc: NotRequired[Union[str, Sequence[str]]] + headers: NotRequired[Mapping[str, str]] + tags: NotRequired[Sequence[EmailTag]] + attachments: NotRequired[Sequence[EmailAttachment]] + capture_engagement: NotRequired[bool] + template_data: NotRequired[Mapping[str, Any]] + + +@dataclass(frozen=True) +class _PreparedUpload: + path: str + body: bytes + + @dataclass(frozen=True) class _PreparedSend: path: str body: bytes idempotency_key: str + upload: Optional[_PreparedUpload] = None + + +def _prepare(args: Mapping[str, Any]) -> _PreparedSend: + is_template_form = "template_id" in args + if is_template_form == ("template_key" in args): + raise TypeError("Pass either template_id or template_key.") + form = TemplateEmailArgs if is_template_form else CodeEmailArgs + unexpected = sorted(set(args) - set(form.__annotations__)) + if unexpected: + raise TypeError( + f"send() got arguments that the {'template' if is_template_form else 'code'} " + f"form doesn't take: {', '.join(unexpected)}." + ) + if "to" not in args: + raise TypeError("send() is missing the argument to.") + if is_template_form: + return _prepare_send( + args["to"], + args["template_id"], + args.get("template_data"), + args.get("distinct_id"), + args.get("idempotency_key"), + ) + return _prepare_code_send(args) + + +def _prepare_code_send(args: Mapping[str, Any]) -> _PreparedSend: + if "subject" not in args: + raise TypeError("send() is missing the argument subject.") + to, distinct_id, idempotency_key = _recipient( + args["to"], args.get("distinct_id"), args.get("idempotency_key") + ) + template_key = args["template_key"] + if not isinstance(template_key, str) or not _TEMPLATE_KEY.fullmatch(template_key): + raise ValueError( + "template_key can only have letters, digits, hyphens (-) and underscores (_), at most 400." + ) + content = {"subject": _nonempty_text(args, "subject")} + content.update( + {field: _string(args, field) for field in ("html", "text") if field in args} + ) + if "html" not in content and "text" not in content: + raise TypeError("send() needs html, text or both.") + if not (content.get("html") or content.get("text")): + raise ValueError("html or text must be a nonempty string.") + + payload: dict[str, Any] = {"to": to} + upload = None + if "template_data" in args: + template_data = args["template_data"] + if not isinstance(template_data, Mapping): + raise TypeError("template_data must be a mapping.") + payload["template"] = {"key": template_key, "hash": _content_hash(content)} + payload["message_data"] = clean(dict(template_data)) + upload = _PreparedUpload( + path=_UPLOAD_PATH.format(template_key=template_key), + body=_encode( + { + "name": template_key, + **content, + "if_not_superseded": True, + "if_code_managed": True, + } + ), + ) + else: + payload.update({"template_key": template_key, **content}) + payload.update(_sender(args)) + if distinct_id is not None: + payload["identifiers"] = {"distinct_id": distinct_id} + return _PreparedSend( + path=_CODE_SEND_PATH, + body=_encode(payload), + idempotency_key=idempotency_key, + upload=upload, + ) + + +def _content_hash(content: Mapping[str, str]) -> str: + """PostHog's content hash v1 of a template, so a send can say which content it holds.""" + encoded = bytearray(_CONTENT_HASH_HEADER) + for field in ("subject", "preheader", "html", "text"): + value = content.get(field, "").replace("\r\n", "\n").replace("\r", "\n") + data = value.encode("utf-8") + encoded += f"{len(data)}:".encode() + data + b"\n" + return "v1:" + hashlib.sha256(encoded).hexdigest() + + +def _sender(args: Mapping[str, Any]) -> dict[str, Any]: + sender: dict[str, Any] = {} + if "from_" in args: + sender["from"] = _nonempty_text(args, "from_") + for field in ("reply_to", "cc", "bcc"): + if field in args: + sender[field] = _addresses(field, args[field]) + if "headers" in args: + sender["headers"] = _headers_field(args["headers"]) + if "tags" in args: + sender["tags"] = _tags(args["tags"]) + if "attachments" in args: + sender["attachments"] = _attachments(args["attachments"]) + if "capture_engagement" in args: + if not isinstance(args["capture_engagement"], bool): + raise TypeError("capture_engagement must be True or False.") + sender["capture_engagement"] = args["capture_engagement"] + return sender + + +def _addresses(field: str, value: Any) -> list[str]: + addresses = [value] if isinstance(value, str) else value + if not isinstance(addresses, Sequence) or not all( + isinstance(address, str) for address in addresses + ): + raise TypeError(f"{field} must be one address or a list of addresses.") + if not all(address.strip() for address in addresses): + raise ValueError(f"{field} must not hold a blank address.") + return list(addresses) + + +def _headers_field(headers: Any) -> dict[str, str]: + if not isinstance(headers, Mapping) or not all( + isinstance(name, str) and isinstance(value, str) + for name, value in headers.items() + ): + raise TypeError("headers must map header names to string values.") + return dict(headers) + + +def _tags(tags: Any) -> list[dict[str, str]]: + if ( + isinstance(tags, str) + or not isinstance(tags, Sequence) + or not all(_is_tag(tag) for tag in tags) + ): + raise TypeError("tags must be a list of {'name': str, 'value': str}.") + return [{"name": tag["name"], "value": tag["value"]} for tag in tags] + + +def _attachments(attachments: Any) -> list[dict[str, str]]: + if isinstance(attachments, (str, bytes)) or not isinstance(attachments, Sequence): + raise TypeError("attachments must be a list of files.") + return [_attachment(index, file) for index, file in enumerate(attachments)] + + +def _attachment(index: int, file: Any) -> dict[str, str]: + name = f"attachments[{index}]" + if not isinstance(file, Mapping) or not {"filename", "content"} <= set(file): + raise TypeError(f"{name} needs a filename and its content.") + unexpected = set(file) - set(EmailAttachment.__annotations__) + if unexpected: + raise TypeError( + f"{name} has fields an attachment doesn't take: {', '.join(sorted(unexpected))}." + ) + if not all(isinstance(file[field], str) for field in file if field != "content"): + raise TypeError( + f"{name} needs its filename, content_type and content_id as strings." + ) + return {**file, "content": _base64_content(name, file["content"])} + + +def _base64_content(name: str, content: Any) -> str: + if isinstance(content, (bytes, bytearray, memoryview)): + return base64.b64encode(bytes(content)).decode("ascii") + if isinstance(content, str): + return content + raise TypeError( + f"{name}.content must be bytes or a Base64 string. " + "Convert a list of byte values with bytes(content)." + ) + + +def _is_tag(tag: Any) -> bool: + return ( + isinstance(tag, Mapping) + and set(tag) == {"name", "value"} + and isinstance(tag["name"], str) + and isinstance(tag["value"], str) + ) + + +def _string(args: Mapping[str, Any], name: str) -> str: + value = args[name] + if not isinstance(value, str): + raise TypeError(f"{name} must be a string.") + return value + + +def _nonempty_text(args: Mapping[str, Any], name: str) -> str: + value = _string(args, name) + if not value: + raise ValueError(f"{name} must not be empty.") + return value + + +def _encode(payload: Mapping[str, Any]) -> bytes: + return json.dumps( + payload, cls=DatetimeSerializer, separators=(",", ":"), ensure_ascii=False + ).encode("utf-8") def _prepare_send( @@ -166,10 +520,7 @@ def _prepare_send( distinct_id: Optional[str], idempotency_key: Optional[str], ) -> _PreparedSend: - if not isinstance(to, str): - raise TypeError("to must be one email address as a string.") - if not to.strip(): - raise ValueError("to must not be empty.") + to, distinct_id, idempotency_key = _recipient(to, distinct_id, idempotency_key) try: template_uuid = ( template_id if isinstance(template_id, UUID) else UUID(template_id) @@ -178,18 +529,6 @@ def _prepare_send( raise ValueError("template_id must be the template's UUID.") from None if template_data is not None and not isinstance(template_data, Mapping): raise TypeError("template_data must be a mapping.") - if distinct_id is not None and ( - not isinstance(distinct_id, str) or not distinct_id - ): - raise ValueError("distinct_id must be a nonempty string.") - if idempotency_key is None: - idempotency_key = str(uuid4()) - elif not isinstance(idempotency_key, str) or not _IDEMPOTENCY_KEY.match( - idempotency_key - ): - raise ValueError( - "idempotency_key must be 1 to 255 visible ASCII characters without spaces." - ) payload: dict[str, Any] = { "to": to, @@ -204,6 +543,28 @@ def _prepare_send( ) +def _recipient( + to: Any, distinct_id: Any, idempotency_key: Any +) -> tuple[str, Optional[str], str]: + if not isinstance(to, str): + raise TypeError("to must be one email address as a string.") + if not to.strip(): + raise ValueError("to must not be empty.") + if distinct_id is not None and ( + not isinstance(distinct_id, str) or not distinct_id + ): + raise ValueError("distinct_id must be a nonempty string.") + if idempotency_key is None: + idempotency_key = str(uuid4()) + elif not isinstance(idempotency_key, str) or not _IDEMPOTENCY_KEY.match( + idempotency_key + ): + raise ValueError( + "idempotency_key must be 1 to 255 visible ASCII characters without spaces." + ) + return to, distinct_id, idempotency_key + + def _validate_options(timeout: float, max_retries: int) -> None: if ( isinstance(timeout, bool) @@ -237,9 +598,9 @@ def _error_name(status: Optional[int], code: str) -> str: return "not_found" if status == 409: return ( - "validation_error" - if code == "template_outdated" - else "concurrent_idempotent_requests" + "concurrent_idempotent_requests" + if code in _IN_FLIGHT_CODES + else "validation_error" ) if status == 422: return "invalid_idempotent_request" @@ -291,8 +652,20 @@ def _parse_response( if isinstance(warning, dict) ), ) + raise _api_error(status, fields, retry_after_header) + + +def _parse_upload(status: int, payload: Any, retry_after_header: Optional[str]) -> None: + if not 200 <= status < 300: + fields = payload if isinstance(payload, dict) else {} + raise _api_error(status, fields, retry_after_header) + + +def _api_error( + status: int, fields: Mapping[str, Any], retry_after_header: Optional[str] +) -> EmailError: code = _text(fields.get("code")) or "api_error" - raise EmailError( + return EmailError( name=_error_name(status, code), code=code, message=_text(fields.get("detail")) or f"PostHog answered HTTP {status}.", @@ -330,23 +703,33 @@ def _no_op() -> None: pass +def _is_outdated(error: EmailError) -> bool: + return error.status_code == 409 and error.code == "template_outdated" + + def _log_warnings(result: SendEmailResult) -> None: for warning in result.warnings: log.warning("PostHog email warning %s: %s", warning.code, warning.message) -def _headers(secret_key: str, idempotency_key: str) -> dict[str, str]: - return { +def _headers(secret_key: str, idempotency_key: Optional[str]) -> dict[str, str]: + headers = { "Authorization": f"Bearer {secret_key}", "Accept": "application/json", "Content-Type": "application/json", - "Idempotency-Key": idempotency_key, "User-Agent": f"posthog-python/{VERSION}", } + if idempotency_key is not None: + headers["Idempotency-Key"] = idempotency_key + return headers + + +_ResultT = TypeVar("_ResultT") +_Parse = Callable[[int, Any, Optional[str]], _ResultT] class _BearerAuth(requests.auth.AuthBase): - def __init__(self, secret_key: str, idempotency_key: str) -> None: + def __init__(self, secret_key: str, idempotency_key: Optional[str]) -> None: self._headers = _headers(secret_key, idempotency_key) def __call__(self, request: requests.PreparedRequest) -> requests.PreparedRequest: @@ -399,7 +782,7 @@ def _secret_key(self) -> str: class Emails(_EmailsBase): - """Sends transactional email from PostHog email templates. + """Sends transactional email from PostHog email templates or from content in your code. ``host`` is your PostHog app host. PostHog Cloud ingestion hosts map to the app host, so ``us.i.posthog.com`` sends to ``us.posthog.com``. Any other @@ -433,16 +816,19 @@ def __init__( self._owns_session = session is None self._session_lock = threading.Lock() - def send( - self, - *, - to: str, - template_id: Union[str, UUID], - template_data: Optional[Mapping[str, Any]] = None, - distinct_id: Optional[str] = None, - idempotency_key: Optional[str] = None, - ) -> SendEmailResult: - """Queue one email from a transactional email template. + @overload + def send(self, **kwargs: Unpack[TemplateEmailArgs]) -> SendEmailResult: ... + + @overload + def send(self, **kwargs: Unpack[CodeEmailArgs]) -> SendEmailResult: ... + + def send(self, **kwargs: Any) -> SendEmailResult: + """Queue one email, from a template in PostHog or from content in your code. + + Pass exactly one form. The template form names a template made in + PostHog with ``template_id``. The code form names the email with + ``template_key`` and passes ``subject`` and ``html``, ``text`` or both: + see :class:`CodeEmailArgs`. Args: to: One recipient email address. @@ -478,11 +864,16 @@ def send( distinct_id="user_123", idempotency_key="welcome:user_123", ) + emails.send( + to="user@example.com", + template_key="password-reset", + subject="Reset your password", + html=rendered_html, + distinct_id="user_123", + ) ``` """ - prepared = _prepare_send( - to, template_id, template_data, distinct_id, idempotency_key - ) + prepared = _prepare(kwargs) if self._is_disabled(): log.debug("PostHog client is disabled, so no email was sent.") return SendEmailResult(id=None) @@ -493,15 +884,44 @@ def send( finish() def _deliver(self, prepared: _PreparedSend) -> SendEmailResult: - auth = _BearerAuth(self._secret_key(), prepared.idempotency_key) + secret_key = self._secret_key() + auth = _BearerAuth(secret_key, prepared.idempotency_key) + try: + result = self._request( + "POST", prepared.path, prepared.body, auth, _parse_response + ) + except EmailError as error: + if prepared.upload is None or not _is_outdated(error): + raise + self._request( + "PUT", + prepared.upload.path, + prepared.upload.body, + _BearerAuth(secret_key, None), + _parse_upload, + ) + result = self._request( + "POST", prepared.path, prepared.body, auth, _parse_response + ) + _log_warnings(result) + return result + + def _request( + self, + method: str, + path: str, + body: bytes, + auth: _BearerAuth, + parse: _Parse[_ResultT], + ) -> _ResultT: session = self._get_session() - url = self.host + prepared.path + url = self.host + path for attempt in range(self.max_retries + 1): try: response = session.request( - "POST", + method, url, - data=prepared.body, + data=body, auth=auth, timeout=self.timeout, allow_redirects=False, @@ -511,15 +931,13 @@ def _deliver(self, prepared: _PreparedSend) -> SendEmailResult: payload = response.json() except ValueError: payload = None - result = _parse_response( + return parse( response.status_code, payload, response.headers.get("Retry-After"), ) finally: response.close() - _log_warnings(result) - return result except requests.exceptions.RequestException: error = _sdk_error("network_error", "The request to PostHog failed.") except EmailError as exc: @@ -585,16 +1003,14 @@ def __init__( self._client: Any = http_client self._owns_client = http_client is None - async def send( - self, - *, - to: str, - template_id: Union[str, UUID], - template_data: Optional[Mapping[str, Any]] = None, - distinct_id: Optional[str] = None, - idempotency_key: Optional[str] = None, - ) -> SendEmailResult: - """Queue one email from a transactional email template. + @overload + async def send(self, **kwargs: Unpack[TemplateEmailArgs]) -> SendEmailResult: ... + + @overload + async def send(self, **kwargs: Unpack[CodeEmailArgs]) -> SendEmailResult: ... + + async def send(self, **kwargs: Any) -> SendEmailResult: + """Queue one email, from a template in PostHog or from content in your code. Takes the same arguments and raises the same errors as :meth:`Emails.send`. @@ -609,9 +1025,7 @@ async def send( ) ``` """ - prepared = _prepare_send( - to, template_id, template_data, distinct_id, idempotency_key - ) + prepared = _prepare(kwargs) if self._is_disabled(): log.debug("PostHog client is disabled, so no email was sent.") return SendEmailResult(id=None) @@ -622,28 +1036,55 @@ async def send( finish() async def _deliver(self, prepared: _PreparedSend) -> SendEmailResult: - headers = _headers(self._secret_key(), prepared.idempotency_key) + secret_key = self._secret_key() + headers = _headers(secret_key, prepared.idempotency_key) + try: + result = await self._request( + "POST", prepared.path, prepared.body, headers, _parse_response + ) + except EmailError as error: + if prepared.upload is None or not _is_outdated(error): + raise + await self._request( + "PUT", + prepared.upload.path, + prepared.upload.body, + _headers(secret_key, None), + _parse_upload, + ) + result = await self._request( + "POST", prepared.path, prepared.body, headers, _parse_response + ) + _log_warnings(result) + return result + + async def _request( + self, + method: str, + path: str, + body: bytes, + headers: Mapping[str, str], + parse: _Parse[_ResultT], + ) -> _ResultT: httpx, client = self._get_client() - url = self.host + prepared.path + url = self.host + path for attempt in range(self.max_retries + 1): try: - response = await client.post( - url, content=prepared.body, headers=headers + response = await client.request( + method, url, content=body, headers=headers ) try: try: payload = response.json() except ValueError: payload = None - result = _parse_response( + return parse( response.status_code, payload, response.headers.get("Retry-After"), ) finally: await response.aclose() - _log_warnings(result) - return result except httpx.RequestError: error = _sdk_error("network_error", "The request to PostHog failed.") except EmailError as exc: diff --git a/posthog/test/test_emails.py b/posthog/test/test_emails.py index 077fdcce0..b7bb8167c 100644 --- a/posthog/test/test_emails.py +++ b/posthog/test/test_emails.py @@ -449,3 +449,417 @@ async def handler(request: httpx.Request) -> httpx.Response: with pytest.raises(EmailError) as raised: await emails.send(to="user@example.com", template_id=TEMPLATE_ID) assert raised.value.code == "client_closed" + + +CODE_SEND_URL = "https://us.posthog.com/api/projects/@current/messaging/send/email/" +HTML = "

Reset it here.

" + + +def send_code(emails: Emails, **overrides: Any): + return emails.send( + **{ + "to": "user@example.com", + "template_key": "password-reset", + "subject": "Reset your password", + **overrides, + } + ) + + +@parameterized.expand( + [ + ("html_only", {"html": HTML}, {"html": HTML}), + ("text_only", {"text": "Reset it here."}, {"text": "Reset it here."}), + ( + "every_field", + { + "html": HTML, + "text": "Reset it here.", + "from_": "Acme ", + "reply_to": "help@example.com", + "capture_engagement": False, + "distinct_id": "user_123", + }, + { + "html": HTML, + "text": "Reset it here.", + "from": "Acme ", + "reply_to": ["help@example.com"], + "capture_engagement": False, + "identifiers": {"distinct_id": "user_123"}, + }, + ), + ( + "several_reply_to", + {"html": HTML, "reply_to": ["a@example.com", "b@example.com"]}, + {"html": HTML, "reply_to": ["a@example.com", "b@example.com"]}, + ), + ( + "empty_address_lists", + {"html": HTML, "reply_to": [], "cc": [], "bcc": []}, + {"html": HTML, "reply_to": [], "cc": [], "bcc": []}, + ), + ] +) +def test_rendered_content_is_posted_as_is(_name, overrides, extra_body): + emails, adapter = emails_with([accepted("msg_1")]) + + result = send_code(emails, idempotency_key="reset:user_123", **overrides) + + assert result.id == "msg_1" + [request] = adapter.requests + assert (request.method, request.url) == ("POST", CODE_SEND_URL) + assert request.headers["Idempotency-Key"] == "reset:user_123" + assert json.loads(request.body) == { + "to": "user@example.com", + "template_key": "password-reset", + "subject": "Reset your password", + **extra_body, + } + + +WELCOME = { + "template_key": "welcome", + "subject": "Welcome, {{ variables.first_name }}", + "html": "

Hi {{ variables.first_name }}

", +} +# The server's content_hash v1 test vectors, shared with posthog-node. +WELCOME_HASH = "v1:f74cd913f3aa2e5667a588f2865634e56693df77793ca594d18e9b5f89e3d2e6" +WELCOME_CRLF_TEXT_HASH = ( + "v1:8112876ee1b2dd7327f571b04b546ed057bfff5a904d9f0ae507b6a449ab6453" +) +UPLOAD_URL = ( + "https://us.posthog.com/api/projects/@current/messaging_templates/by_key/welcome/" +) + + +def send_local_template(emails: Emails, **overrides: Any): + return emails.send( + **{ + "to": "user@example.com", + **WELCOME, + "template_data": {"first_name": "Jane"}, + **overrides, + } + ) + + +@parameterized.expand( + [ + ("html_only", {}, WELCOME_HASH), + ("crlf_text", {"text": "\r\n\r"}, WELCOME_CRLF_TEXT_HASH), + ("empty_text", {"text": ""}, WELCOME_HASH), + ] +) +def test_a_local_template_is_sent_by_key_and_content_hash(_name, overrides, hash): + emails, adapter = emails_with([accepted("msg_1")]) + + result = send_local_template( + emails, from_="Acme ", distinct_id="user_123", **overrides + ) + + assert result.id == "msg_1" + [request] = adapter.requests + assert (request.method, request.url) == ("POST", CODE_SEND_URL) + assert json.loads(request.body) == { + "to": "user@example.com", + "template": {"key": "welcome", "hash": hash}, + "message_data": {"first_name": "Jane"}, + "from": "Acme ", + "identifiers": {"distinct_id": "user_123"}, + } + + +def uploaded() -> Reply: + return (201, {"id": "tpl_1", "key": "welcome", "result": "created"}, {}) + + +def test_an_outdated_local_template_is_uploaded_then_sent_again_with_the_same_key(): + emails, adapter = emails_with( + [rejected(409, "template_outdated"), uploaded(), accepted("msg_1")] + ) + + result = send_local_template(emails, text="Hi {{ variables.first_name }}") + + assert result.id == "msg_1" + first_send, upload, second_send = adapter.requests + assert (upload.method, upload.url) == ("PUT", UPLOAD_URL) + assert json.loads(upload.body) == { + "name": "welcome", + "subject": "Welcome, {{ variables.first_name }}", + "html": "

Hi {{ variables.first_name }}

", + "text": "Hi {{ variables.first_name }}", + "if_not_superseded": True, + "if_code_managed": True, + } + assert "Idempotency-Key" not in upload.headers + assert upload.headers["Authorization"] == f"Bearer {SECRET_KEY}" + assert second_send.body == first_send.body + assert ( + second_send.headers["Idempotency-Key"] == first_send.headers["Idempotency-Key"] + ) + + +@parameterized.expand( + [ + ("refused_upload", rejected(409, "template_edited_in_posthog"), 2), + ("outdated_again", None, 3), + ] +) +def test_a_local_template_uploads_at_most_once_per_send( + _name, upload_reply, requests_made +): + replies = ( + [rejected(409, "template_outdated"), upload_reply] + if upload_reply + else [ + rejected(409, "template_outdated"), + uploaded(), + rejected(409, "template_outdated"), + ] + ) + emails, adapter = emails_with(replies) + + with pytest.raises(EmailError) as raised: + send_local_template(emails) + + assert (raised.value.status_code, raised.value.name) == (409, "validation_error") + assert len(adapter.requests) == requests_made + + +def test_rendered_content_is_never_uploaded(): + emails, adapter = emails_with([rejected(409, "template_outdated")]) + + with pytest.raises(EmailError): + send_code(emails, html=HTML) + + assert [request.method for request in adapter.requests] == ["POST"] + + +@pytest.mark.asyncio +async def test_async_uploads_an_outdated_local_template_then_sends_again(): + seen: list[httpx.Request] = [] + replies = [ + httpx.Response(409, json={"code": "template_outdated"}), + httpx.Response(201, json={"id": "tpl_1", "result": "created"}), + httpx.Response(202, json={"message_id": "msg_1"}), + ] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append(request) + return replies.pop(0) + + async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client: + result = await AsyncEmails(SECRET_KEY, http_client=client).send( + to="user@example.com", **WELCOME, template_data={"first_name": "Jane"} + ) + + assert result.id == "msg_1" + assert [(request.method, str(request.url)) for request in seen] == [ + ("POST", CODE_SEND_URL), + ("PUT", UPLOAD_URL), + ("POST", CODE_SEND_URL), + ] + first_send, upload, second_send = seen + assert json.loads(first_send.content)["template"] == { + "key": "welcome", + "hash": WELCOME_HASH, + } + assert "Idempotency-Key" not in upload.headers + assert second_send.content == first_send.content + assert ( + second_send.headers["Idempotency-Key"] == first_send.headers["Idempotency-Key"] + ) + + +@parameterized.expand( + [ + ("both_forms", {"template_id": TEMPLATE_ID, "html": HTML}, TypeError), + ("no_form", {"template_key": None}, TypeError), + ("no_content", {}, TypeError), + ("no_subject", {"subject": None, "html": HTML}, TypeError), + ("subject_not_text", {"subject": 1, "html": HTML}, TypeError), + ("from_not_text", {"html": HTML, "from_": 1}, TypeError), + ("from_keyword", {"html": HTML, "from": "a@example.com"}, TypeError), + ( + "key_with_space", + {"template_key": "reset password", "html": HTML}, + ValueError, + ), + ( + "key_with_trailing_newline", + {"template_key": "welcome\n", "html": HTML}, + ValueError, + ), + ("key_too_long", {"template_key": "k" * 401, "html": HTML}, ValueError), + ("empty_html", {"html": ""}, ValueError), + ("empty_html_and_text", {"html": "", "text": ""}, ValueError), + ("blank_cc", {"html": HTML, "cc": " "}, ValueError), + ("cc_not_text", {"html": HTML, "cc": 123}, TypeError), + ("template_data_list", {"html": HTML, "template_data": [1]}, TypeError), + ( + "cc_on_template_form", + { + "template_id": TEMPLATE_ID, + "template_key": None, + "subject": None, + "cc": "a@example.com", + }, + TypeError, + ), + ] +) +def test_rejects_a_code_send_that_mixes_or_misses_fields(_name, overrides, error): + emails, adapter = emails_with([]) + args = { + "to": "user@example.com", + "template_key": "password-reset", + "subject": "Reset your password", + **overrides, + } + + with pytest.raises(error): + emails.send( + **{name: value for name, value in args.items() if value is not None} + ) + + assert adapter.requests == [] + + +COPIES_HEADERS_AND_TAGS = { + "cc": "manager@example.com", + "bcc": ["audit@example.com", "archive@example.com"], + "headers": {"X-Entity-Ref-ID": "order-123"}, + "tags": [{"name": "category", "value": "password_reset"}], +} +COPIES_HEADERS_AND_TAGS_BODY = { + "cc": ["manager@example.com"], + "bcc": ["audit@example.com", "archive@example.com"], + "headers": {"X-Entity-Ref-ID": "order-123"}, + "tags": [{"name": "category", "value": "password_reset"}], +} + + +def test_rendered_content_carries_copies_headers_and_tags(): + emails, adapter = emails_with([accepted()]) + + send_code(emails, html=HTML, **COPIES_HEADERS_AND_TAGS) + + [request] = adapter.requests + assert json.loads(request.body) == { + "to": "user@example.com", + "template_key": "password-reset", + "subject": "Reset your password", + "html": HTML, + **COPIES_HEADERS_AND_TAGS_BODY, + } + + +def test_a_server_that_does_not_take_a_field_refuses_the_send_and_names_it(): + refused = { + "type": "invalid_request", + "code": "invalid_request", + "detail": "cc: PostHog doesn't take this field on this route.", + "attr": "cc", + } + emails, adapter = emails_with([(400, refused, {}), accepted()]) + + with pytest.raises(EmailError) as raised: + send_code(emails, html=HTML, cc="manager@example.com") + + error = raised.value + assert (error.name, error.code, error.field) == ( + "validation_error", + "invalid_request", + "cc", + ) + assert len(adapter.requests) == 1 + + +def test_a_local_template_sends_copies_headers_and_tags_but_never_uploads_them(): + emails, adapter = emails_with( + [rejected(409, "template_outdated"), uploaded(), accepted()] + ) + + send_local_template(emails, **COPIES_HEADERS_AND_TAGS) + + first_send, upload, _ = adapter.requests + sent = json.loads(first_send.body) + assert {field: sent[field] for field in COPIES_HEADERS_AND_TAGS_BODY} == ( + COPIES_HEADERS_AND_TAGS_BODY + ) + assert not set(COPIES_HEADERS_AND_TAGS_BODY) & set(json.loads(upload.body)) + + +INVITE = b"BEGIN:VCALENDAR\r\nEND:VCALENDAR\r\n" + + +def test_attachments_are_sent_base64_encoded_once_across_retries(): + emails, adapter = emails_with([rejected(503, "delivery_unavailable"), accepted()]) + + send_code( + emails, + html=HTML, + attachments=[ + { + "filename": "invite.ics", + "content": INVITE, + "content_type": "text/calendar; method=REQUEST", + }, + {"filename": "logo.png", "content": "iVBORw0KGgo=", "content_id": "logo"}, + ], + ) + + first, retry = adapter.requests + assert json.loads(first.body)["attachments"] == [ + { + "filename": "invite.ics", + "content": "QkVHSU46VkNBTEVOREFSDQpFTkQ6VkNBTEVOREFSDQo=", + "content_type": "text/calendar; method=REQUEST", + }, + {"filename": "logo.png", "content": "iVBORw0KGgo=", "content_id": "logo"}, + ] + assert retry.body == first.body + + +@parameterized.expand( + [ + ("bytearray", bytearray(INVITE)), + ("memoryview", memoryview(INVITE)), + ( + "strided_memoryview", + memoryview(bytes(b for byte in INVITE for b in (byte, 0)))[::2], + ), + ] +) +def test_attachment_content_from_any_bytes_buffer_is_base64_encoded(_name, content): + emails, adapter = emails_with([accepted()]) + + send_code( + emails, html=HTML, attachments=[{"filename": "invite.ics", "content": content}] + ) + + [request] = adapter.requests + assert json.loads(request.body)["attachments"] == [ + { + "filename": "invite.ics", + "content": "QkVHSU46VkNBTEVOREFSDQpFTkQ6VkNBTEVOREFSDQo=", + } + ] + + +@parameterized.expand( + [ + ("list_of_ints", {"filename": "a.txt", "content": [104, 105]}), + ("no_filename", {"content": b"104"}), + ("unknown_field", {"filename": "a.txt", "content": b"104", "path": "/tmp/a"}), + ] +) +def test_rejects_an_attachment_that_is_not_a_file(_name, attachment): + emails, adapter = emails_with([]) + + with pytest.raises(TypeError) as raised: + send_code(emails, html=HTML, attachments=[attachment]) + + assert "104" not in str(raised.value) + assert adapter.requests == [] diff --git a/references/public_api_snapshot.txt b/references/public_api_snapshot.txt index 7bd9a74ce..c1fd1b560 100644 --- a/references/public_api_snapshot.txt +++ b/references/public_api_snapshot.txt @@ -818,6 +818,23 @@ attribute posthog.debug = False attribute posthog.default_client = None attribute posthog.disable_geoip = True attribute posthog.disabled = False +attribute posthog.emails.CodeEmailArgs.attachments: NotRequired[Sequence[EmailAttachment]] +attribute posthog.emails.CodeEmailArgs.bcc: NotRequired[Union[str, Sequence[str]]] +attribute posthog.emails.CodeEmailArgs.capture_engagement: NotRequired[bool] +attribute posthog.emails.CodeEmailArgs.cc: NotRequired[Union[str, Sequence[str]]] +attribute posthog.emails.CodeEmailArgs.from_: NotRequired[str] +attribute posthog.emails.CodeEmailArgs.headers: NotRequired[Mapping[str, str]] +attribute posthog.emails.CodeEmailArgs.html: NotRequired[str] +attribute posthog.emails.CodeEmailArgs.reply_to: NotRequired[Union[str, Sequence[str]]] +attribute posthog.emails.CodeEmailArgs.subject: str +attribute posthog.emails.CodeEmailArgs.tags: NotRequired[Sequence[EmailTag]] +attribute posthog.emails.CodeEmailArgs.template_data: NotRequired[Mapping[str, Any]] +attribute posthog.emails.CodeEmailArgs.template_key: str +attribute posthog.emails.CodeEmailArgs.text: NotRequired[str] +attribute posthog.emails.EmailAttachment.content: Union[bytes, bytearray, memoryview, str] +attribute posthog.emails.EmailAttachment.content_id: NotRequired[str] +attribute posthog.emails.EmailAttachment.content_type: NotRequired[str] +attribute posthog.emails.EmailAttachment.filename: str attribute posthog.emails.EmailError.code = code attribute posthog.emails.EmailError.docs_url = docs_url attribute posthog.emails.EmailError.field = field @@ -827,12 +844,16 @@ attribute posthog.emails.EmailError.name = name attribute posthog.emails.EmailError.retry_after = retry_after attribute posthog.emails.EmailError.status_code = status_code attribute posthog.emails.EmailError.why = why +attribute posthog.emails.EmailTag.name: str +attribute posthog.emails.EmailTag.value: str attribute posthog.emails.EmailWarning.code: str attribute posthog.emails.EmailWarning.fix: Optional[str] = None attribute posthog.emails.EmailWarning.message: str attribute posthog.emails.SendEmailResult.id: Optional[str] attribute posthog.emails.SendEmailResult.replayed: bool = False attribute posthog.emails.SendEmailResult.warnings: tuple[EmailWarning, ...] = () +attribute posthog.emails.TemplateEmailArgs.template_data: NotRequired[Optional[Mapping[str, Any]]] +attribute posthog.emails.TemplateEmailArgs.template_id: Union[str, UUID] attribute posthog.enable_exception_autocapture = False attribute posthog.enable_exception_autocapture_rate_limiting = False attribute posthog.enable_full_ai_capture = False @@ -1239,10 +1260,14 @@ class posthog.client.Client(project_api_key: str, host=None, debug=False, max_qu class posthog.consumer.Consumer(queue, api_key, flush_at=100, host=None, on_error=None, flush_interval=5.0, gzip=False, retries=10, timeout=15, historical_migration=False, endpoint=EVENTS_ENDPOINT, max_msg_size=MAX_MSG_SIZE, capture_mode=CaptureMode.V0, capture_compression=CaptureCompression.NONE) class posthog.contexts.ContextScope(parent=None, fresh: bool = False, capture_exceptions: bool = True, client: Optional[Client] = None) class posthog.emails.AsyncEmails(secret_key: Optional[str], *, host: Optional[str] = None, timeout: float = 15, max_retries: int = 2, disabled: bool = False, http_client: Any = None) +class posthog.emails.CodeEmailArgs +class posthog.emails.EmailAttachment class posthog.emails.EmailError(*, name: str, code: str, message: str, status_code: Optional[int] = None, why: Optional[str] = None, fix: Optional[str] = None, docs_url: Optional[str] = None, field: Optional[str] = None, retry_after: Optional[float] = None) +class posthog.emails.EmailTag class posthog.emails.EmailWarning(code: str, message: str, fix: Optional[str] = None) class posthog.emails.Emails(secret_key: Optional[str], *, host: Optional[str] = None, timeout: float = 15, max_retries: int = 2, disabled: bool = False, session: Optional[requests.Session] = None) class posthog.emails.SendEmailResult(id: Optional[str], replayed: bool = False, warnings: tuple[EmailWarning, ...] = ()) +class posthog.emails.TemplateEmailArgs class posthog.exception_capture.ExceptionCapture(client: Client, rate_limiting_enabled=False, bucket_size=DEFAULT_BUCKET_SIZE, refill_rate=DEFAULT_REFILL_RATE, refill_interval_seconds=DEFAULT_REFILL_INTERVAL_SECONDS) class posthog.exception_utils.AnnotatedValue(value, metadata) class posthog.exception_utils.VariableSizeLimiter(max_size=DEFAULT_TOTAL_VARIABLES_SIZE_LIMIT) @@ -1704,9 +1729,9 @@ method posthog.contexts.ContextScope.set_device_id(device_id: str) method posthog.contexts.ContextScope.set_distinct_id(distinct_id: str) method posthog.contexts.ContextScope.set_session_id(session_id: str) method posthog.emails.AsyncEmails.aclose() -> None -method posthog.emails.AsyncEmails.send(*, to: str, template_id: Union[str, UUID], template_data: Optional[Mapping[str, Any]] = None, distinct_id: Optional[str] = None, idempotency_key: Optional[str] = None) -> SendEmailResult +method posthog.emails.AsyncEmails.send(**kwargs: Any) -> SendEmailResult method posthog.emails.Emails.close() -> None -method posthog.emails.Emails.send(*, to: str, template_id: Union[str, UUID], template_data: Optional[Mapping[str, Any]] = None, distinct_id: Optional[str] = None, idempotency_key: Optional[str] = None) -> SendEmailResult +method posthog.emails.Emails.send(**kwargs: Any) -> SendEmailResult method posthog.exception_capture.ExceptionCapture.capture_exception(exception, metadata=None) method posthog.exception_capture.ExceptionCapture.close() method posthog.exception_capture.ExceptionCapture.exception_handler(exc_type, exc_value, exc_traceback)