diff --git a/.github/scripts/check_strict_types.sh b/.github/scripts/check_strict_types.sh
index d1647516b..149b10d86 100755
--- a/.github/scripts/check_strict_types.sh
+++ b/.github/scripts/check_strict_types.sh
@@ -12,6 +12,7 @@ python -m venv "$tmp/.venv"
cat > "$tmp/strict_posthog_types.py" <<'PY'
# pyright: strict
import atexit
+from datetime import datetime, timezone
import posthog
from posthog import FeatureFlagEvaluations, FlagValue, Posthog
@@ -50,11 +51,14 @@ invite_send: SendEmailResult = emails.send(to="user@example.com", template_key="
tracked_send: SendEmailResult = emails.send(to="user@example.com", template_key="welcome", subject="Welcome", html="
Hi
", tracking={"clicks": True, "engagement": False})
untracked_send: SendEmailResult = emails.send(to="user@example.com", template_key="welcome", subject="Welcome", html="Hi
", tracking=False)
not_sensitive_send: SendEmailResult = emails.send(to="user@example.com", template_key="newsletter", subject="News", html="News
", sensitive=False)
-_ = (template_send, rendered_send, invite_send, tracked_send, untracked_send, not_sensitive_send)
+scheduled_send: SendEmailResult = emails.send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", scheduled_at=datetime(2026, 12, 1, tzinfo=timezone.utc))
+scheduled_status: str = scheduled_send.status
+scheduled_time: datetime | None = scheduled_send.scheduled_at
+_ = (template_send, rendered_send, invite_send, tracked_send, untracked_send, not_sensitive_send, scheduled_status, scheduled_time)
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: SendEmailResult = await AsyncEmails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="Hi
", scheduled_at="2026-12-01T09:00:00Z")
_ = sent
@@ -114,6 +118,7 @@ Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3
Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", sensitive=False) # expected-type-error
Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="Hi
", tracking={"open": False}) # expected-type-error
Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="Hi
", template_data={"name": "Ada"}) # expected-type-error
+Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="Hi
", scheduled_at=1796115600) # 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
Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="Hi
", attachments=[{"filename": "a.txt", "content": b"hi", "path": "/tmp/a.txt"}]) # expected-type-error
Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", attachments=[{"filename": "a.txt", "content": b"hi"}]) # expected-type-error
diff --git a/.sampo/changesets/scheduled-email-sends.md b/.sampo/changesets/scheduled-email-sends.md
new file mode 100644
index 000000000..338ded9f2
--- /dev/null
+++ b/.sampo/changesets/scheduled-email-sends.md
@@ -0,0 +1,5 @@
+---
+pypi/posthog: minor
+---
+
+Schedule a transactional email with `scheduled_at` on `emails.send()`, up to 7 days ahead, on PostHog Cloud. A naive `datetime`, a string without an offset, or a client whose host isn't PostHog Cloud (`scheduling_requires_cloud`) raises before any request. The client rounds the time up to the millisecond and checks that PostHog confirmed it, raising `schedule_not_confirmed` with the email's `message_id` otherwise. Send results now carry `status` and `scheduled_at`.
diff --git a/posthog/emails.py b/posthog/emails.py
index c180a9224..6db60413b 100644
--- a/posthog/emails.py
+++ b/posthog/emails.py
@@ -111,6 +111,38 @@
``not_found`` (404) for an unknown ID, an email older than 30 days, or for a
few seconds after the send.
+Scheduling: pass ``scheduled_at``, an aware ``datetime`` or an ISO 8601 string
+such as ``2026-12-01T09:00:00Z`` or ``2026-12-01 11:00:00.5+02:00``, to send the
+email up to 7 days later. Only PostHog Cloud
+schedules emails: on any other app host, such as a reverse proxy or a custom
+domain, a send with ``scheduled_at`` raises ``scheduling_requires_cloud``
+before any request. A naive ``datetime``, or a string that isn't a date, a
+``T`` or a space, a time and ``Z`` or a ``+HH:MM`` offset, raises
+``ValueError`` before any request. The client rounds the time up to the next
+millisecond, so the email never goes out early. A result with ``status``
+``"scheduled"`` carries the confirmed ``scheduled_at``; ``get`` reads
+``scheduled`` until the email goes out. A time that has already passed sends
+the email now, and the result's ``status`` is ``"queued"``. The client accepts
+that answer only for a time at most 60 seconds ahead of its clock at the send's
+first attempt, however long the answer or a retry takes: for a time further
+ahead it raises ``schedule_not_confirmed``, so an email PostHog didn't
+schedule never reads as scheduled or sent on time. Compute the time
+once and reuse it on your own retries: the idempotency key covers it, so the
+same key with another time raises ``idempotency_key_reused``. To stop scheduled
+emails before they go out, disable the email's workflow in PostHog until they
+have reached a final status. That refuses every new send of it meanwhile.
+
+```python
+from datetime import datetime, timedelta, timezone
+
+result = posthog.emails.send(
+ to="user@example.com",
+ template_id="",
+ scheduled_at=datetime.now(timezone.utc) + timedelta(days=1),
+)
+print(result.status, result.scheduled_at) # scheduled, the time in UTC
+```
+
Cleanup: ``shutdown()`` on the client closes its email connections. Close a
standalone :class:`Emails` with ``close()`` or a ``with`` block.
@@ -134,13 +166,14 @@
import re
import threading
import time
-from dataclasses import dataclass
-from datetime import datetime
+from dataclasses import dataclass, replace
+from datetime import datetime, timedelta, timezone
from types import TracebackType
from typing import (
Any,
Awaitable,
Callable,
+ Literal,
Mapping,
Optional,
Sequence,
@@ -216,6 +249,8 @@ class EmailError(Exception):
docs_url: A docs page about the error, when PostHog gave one.
field: The request field the error is about, when there is one.
retry_after: Seconds to wait before retrying, when PostHog said.
+ message_id: The message ID of an email PostHog accepted, when the
+ error is about that email, such as ``schedule_not_confirmed``.
"""
def __init__(
@@ -230,6 +265,7 @@ def __init__(
docs_url: Optional[str] = None,
field: Optional[str] = None,
retry_after: Optional[float] = None,
+ message_id: Optional[str] = None,
) -> None:
super().__init__(message)
self.name = name
@@ -241,6 +277,7 @@ def __init__(
self.docs_url = docs_url
self.field = field
self.retry_after = retry_after
+ self.message_id = message_id
@dataclass(frozen=True)
@@ -252,18 +289,28 @@ class EmailWarning:
@dataclass(frozen=True)
class SendEmailResult:
- """The queued email. ``id`` is its message ID.
+ """The accepted email. ``id`` is its message ID.
Attributes:
id: The email's message ID.
replayed: ``True`` when the response says PostHog replayed an earlier send for
the same ``idempotency_key`` instead of sending again.
warnings: Warnings PostHog returned about the request.
+ status: ``"scheduled"`` when the email waits for its ``scheduled_at``,
+ ``"queued"`` when it goes out now.
+ scheduled_at: When a scheduled email goes out, in UTC. ``None`` for
+ an email that goes out now, also when ``scheduled_at`` had
+ already passed when PostHog accepted it.
"""
id: str
replayed: bool = False
warnings: tuple[EmailWarning, ...] = ()
+ scheduled_at: Optional[datetime] = None
+
+ @property
+ def status(self) -> Literal["queued", "scheduled"]:
+ return "queued" if self.scheduled_at is None else "scheduled"
class EmailAttachment(TypedDict):
@@ -291,6 +338,7 @@ class _RecipientArgs(TypedDict):
distinct_id: NotRequired[Optional[str]]
idempotency_key: NotRequired[Optional[str]]
max_retries: NotRequired[Optional[int]]
+ scheduled_at: NotRequired[Optional[Union[datetime, str]]]
class TemplateEmailArgs(_RecipientArgs):
@@ -305,6 +353,8 @@ class TemplateEmailArgs(_RecipientArgs):
idempotency_key: 1 to 255 visible ASCII characters.
max_retries: Overrides the client's maximum number of retries for this
send. ``0`` turns retries off.
+ scheduled_at: When to send the email, up to 7 days ahead, on PostHog
+ Cloud only. See :meth:`Emails.send`.
"""
template_id: Union[str, UUID]
@@ -399,6 +449,8 @@ class CodeEmailArgs(_RecipientArgs):
first send's result, also when its workflow was paused since.
max_retries: Overrides the client's maximum number of retries for this
send. ``0`` turns retries off.
+ scheduled_at: When to send the email, up to 7 days ahead, on PostHog
+ Cloud only. See :meth:`Emails.send`.
"""
template_key: str
@@ -426,6 +478,7 @@ class CodeEmailArgs(_RecipientArgs):
"bcc",
"attachments",
"capture_engagement",
+ "scheduled_at",
"sensitive",
"tracking",
}
@@ -438,6 +491,7 @@ class EmailStatus:
``status`` is one of:
+ - ``scheduled``: the email waits for its ``scheduled_at``.
- ``queued``: the email waits to go out.
- ``sent``: PostHog handed the email to the email provider.
- ``failed``: the email was not sent, and ``reason`` says why.
@@ -491,6 +545,7 @@ class _PreparedSend:
idempotency_key: str
max_retries: Optional[int] = None
files: tuple[_File, ...] = ()
+ scheduled_at: Optional[datetime] = None
def _prepare(args: Mapping[str, Any]) -> _PreparedSend:
@@ -506,6 +561,7 @@ def _prepare(args: Mapping[str, Any]) -> _PreparedSend:
)
if "to" not in args:
raise TypeError("send() is missing the argument to.")
+ scheduled_at = _requested_time(args.get("scheduled_at"))
if is_template_form:
return _prepare_send(
args["to"],
@@ -514,11 +570,14 @@ def _prepare(args: Mapping[str, Any]) -> _PreparedSend:
args.get("distinct_id"),
args.get("idempotency_key"),
args.get("max_retries"),
+ scheduled_at,
)
- return _prepare_code_send(args)
+ return _prepare_code_send(args, scheduled_at)
-def _prepare_code_send(args: Mapping[str, Any]) -> _PreparedSend:
+def _prepare_code_send(
+ args: Mapping[str, Any], scheduled_at: Optional[datetime]
+) -> _PreparedSend:
args = {
name: value
for name, value in args.items()
@@ -545,12 +604,14 @@ def _prepare_code_send(args: Mapping[str, Any]) -> _PreparedSend:
payload.update(_sender(args))
if references:
payload["attachments"] = references
+ payload.update(_schedule_field(scheduled_at))
return _PreparedSend(
path=_SEND_PATH,
body=_encode(payload),
idempotency_key=idempotency_key,
max_retries=max_retries,
files=_each_file_once(files),
+ scheduled_at=scheduled_at,
)
@@ -816,6 +877,7 @@ def _prepare_send(
distinct_id: Optional[str],
idempotency_key: Optional[str],
max_retries: Optional[int] = None,
+ scheduled_at: Optional[datetime] = None,
) -> _PreparedSend:
to, distinct_id, idempotency_key = _recipient(to, distinct_id, idempotency_key)
max_retries = _retry_limit(max_retries)
@@ -835,11 +897,13 @@ def _prepare_send(
}
if distinct_id is not None:
payload["distinct_id"] = distinct_id
+ payload.update(_schedule_field(scheduled_at))
return _PreparedSend(
path=_SEND_PATH,
body=json.dumps(payload, cls=DatetimeSerializer).encode("utf-8"),
idempotency_key=idempotency_key,
max_retries=max_retries,
+ scheduled_at=scheduled_at,
)
@@ -875,6 +939,73 @@ def _retry_limit(max_retries: Any) -> Optional[int]:
return max_retries
+_TIME_NEEDS_OFFSET = (
+ "scheduled_at must be an ISO 8601 time with a timezone offset, such as "
+ "2026-12-01T09:00:00Z or 2026-12-01T09:00:00+02:00."
+)
+
+
+def _requested_time(value: Any) -> Optional[datetime]:
+ if value is None:
+ return None
+ if isinstance(value, datetime):
+ if value.utcoffset() is None:
+ raise ValueError(
+ "scheduled_at has no timezone, so the email could go out at the wrong "
+ "time. Pass an aware datetime, such as "
+ "datetime.now(timezone.utc) + timedelta(hours=1)."
+ )
+ return _ceil_to_millisecond(value)
+ if isinstance(value, str):
+ parsed = _schedule_time(value)
+ if parsed is None:
+ raise ValueError(_TIME_NEEDS_OFFSET)
+ return _ceil_to_millisecond(parsed)
+ raise TypeError(
+ "scheduled_at must be an aware datetime or an ISO 8601 string with an offset."
+ )
+
+
+def _ceil_to_millisecond(when: datetime) -> datetime:
+ try:
+ return _ceil_to_millisecond_in_utc(when)
+ except OverflowError:
+ raise ValueError(
+ "scheduled_at is past the latest time the client can send. "
+ "PostHog schedules an email up to 7 days ahead."
+ ) from None
+
+
+def _ceil_to_millisecond_in_utc(when: datetime) -> datetime:
+ utc = when.astimezone(timezone.utc)
+ plain = datetime(
+ utc.year,
+ utc.month,
+ utc.day,
+ utc.hour,
+ utc.minute,
+ utc.second,
+ utc.microsecond,
+ tzinfo=timezone.utc,
+ )
+ nanoseconds = getattr(when, "nanosecond", 0)
+ if isinstance(nanoseconds, int) and nanoseconds % 1000:
+ plain += timedelta(microseconds=1)
+ below_a_millisecond = plain.microsecond % 1000
+ if below_a_millisecond:
+ plain += timedelta(microseconds=1000 - below_a_millisecond)
+ return plain
+
+
+def _schedule_field(scheduled_at: Optional[datetime]) -> dict[str, str]:
+ if scheduled_at is None:
+ return {}
+ return {
+ "scheduled_at": f"{scheduled_at:%Y-%m-%dT%H:%M:%S}."
+ f"{scheduled_at.microsecond // 1000:03d}Z"
+ }
+
+
def _status_path(message_id: Union[str, UUID]) -> str:
try:
message_uuid = message_id if isinstance(message_id, UUID) else UUID(message_id)
@@ -974,23 +1105,72 @@ def _json_object(body: bytes) -> dict[str, Any]:
return payload if isinstance(payload, dict) else {}
-def _parse_response(
- status: int, body: bytes, retry_after_header: Optional[str]
-) -> SendEmailResult:
- fields = _json_object(body)
- if 200 <= status < 300:
+def _send_parser(scheduled_at: Optional[datetime]) -> _Parse[SendEmailResult]:
+ first_attempt = _now()
+
+ def parse(
+ status: int, body: bytes, retry_after_header: Optional[str]
+ ) -> SendEmailResult:
+ fields = _json_object(body)
+ if not 200 <= status < 300:
+ raise _response_error(fields, status, retry_after_header)
message_id = _text(fields.get("message_id"))
if message_id is None:
raise _sdk_error(
"api_error", "PostHog answered without a message ID.", status
)
- warnings = fields.get("warnings")
- return SendEmailResult(
+ result = SendEmailResult(
id=message_id,
replayed=fields.get("replayed") is True,
- warnings=_parse_warnings(warnings),
+ warnings=_parse_warnings(fields.get("warnings")),
)
- raise _response_error(fields, status, retry_after_header)
+ if scheduled_at is None:
+ return result
+ if _confirms_schedule(fields, scheduled_at):
+ return replace(result, scheduled_at=scheduled_at)
+ if _sends_now(fields) and scheduled_at - first_attempt <= _SEND_NOW_LEEWAY:
+ return result
+ raise _schedule_not_confirmed(message_id, status)
+
+ return parse
+
+
+def _now() -> datetime:
+ return datetime.now(timezone.utc)
+
+
+_SEND_NOW_LEEWAY = timedelta(seconds=60)
+
+
+def _sends_now(fields: Mapping[str, Any]) -> bool:
+ return (
+ fields.get("status") == "queued"
+ and "scheduled_at" in fields
+ and fields["scheduled_at"] is None
+ )
+
+
+def _confirms_schedule(fields: Mapping[str, Any], requested: datetime) -> bool:
+ answered = fields.get("scheduled_at")
+ return (
+ fields.get("status") == "scheduled"
+ and isinstance(answered, str)
+ and _schedule_time(answered) == requested
+ )
+
+
+def _schedule_not_confirmed(message_id: str, status: int) -> EmailError:
+ return EmailError(
+ name="application_error",
+ code="schedule_not_confirmed",
+ message=f"PostHog accepted email {message_id} without confirming its "
+ "scheduled_at, so it may go out at another time.",
+ status_code=status,
+ fix=f"Read the email's status with emails.get('{message_id}') before you send "
+ "it again: a send with another idempotency_key makes a second email.",
+ field="scheduled_at",
+ message_id=message_id,
+ )
def _parse_warnings(warnings: Any) -> tuple[EmailWarning, ...]:
@@ -1018,6 +1198,35 @@ def _timestamp(value: Any) -> Optional[datetime]:
return None
+_SCHEDULE_TIME = re.compile(
+ r"(?P[0-9]{4}-[0-9]{2}-[0-9]{2})[T ]"
+ r"(?P(?:[01][0-9]|2[0-3]):[0-5][0-9])"
+ r"(?::(?P[0-5][0-9])(?:[.,](?P[0-9]+))?)?"
+ r"(?PZ|[+-](?:[01][0-9]|2[0-3]):[0-5][0-9])"
+)
+
+
+def _schedule_time(text: str) -> Optional[datetime]:
+ written = _SCHEDULE_TIME.fullmatch(text)
+ if written is None:
+ return None
+ offset = "+00:00" if written["offset"] == "Z" else written["offset"]
+ try:
+ return datetime.fromisoformat(
+ f"{written['date']}T{written['hour_and_minute']}:"
+ f"{written['second'] or '00'}{offset}"
+ ) + _fraction_rounded_up(written["fraction"] or "")
+ except (ValueError, OverflowError):
+ return None
+
+
+def _fraction_rounded_up(digits: str) -> timedelta:
+ microseconds = int(digits[:6].ljust(6, "0"))
+ if digits[6:].strip("0"):
+ microseconds += 1
+ return timedelta(microseconds=microseconds)
+
+
def _parse_status_response(
status: int, body: bytes, retry_after_header: Optional[str]
) -> EmailStatus:
@@ -1328,6 +1537,23 @@ def _secret_key(self, key_needed: str) -> str:
raise _sdk_error("missing_secret_key", key_needed)
return self.secret_key
+ def _check_schedulable(self, prepared: _PreparedSend) -> None:
+ if prepared.scheduled_at is None or self.host in (
+ US_APP_ENDPOINT,
+ EU_APP_ENDPOINT,
+ ):
+ return
+ raise EmailError(
+ name="application_error",
+ code="scheduling_requires_cloud",
+ message="Scheduled sends work only on PostHog Cloud (us.posthog.com or "
+ f"eu.posthog.com), and this client sends to {self.host}, so no email was sent.",
+ why="A PostHog that doesn't schedule emails would send this one at once.",
+ fix="Send without scheduled_at, or send through PostHog Cloud's app host. "
+ "A reverse proxy or custom domain can't schedule emails yet.",
+ field="scheduled_at",
+ )
+
class Emails(_EmailsBase):
"""Sends transactional email from PostHog email templates or from content in your code.
@@ -1398,20 +1624,37 @@ def send(self, **kwargs: Any) -> SendEmailResult:
outside this call, too.
max_retries: Overrides the client's maximum number of retries for
this send. ``0`` turns retries off.
+ scheduled_at: When to send the email, up to 7 days ahead: an aware
+ ``datetime``, or an ISO 8601 string with an offset, such as
+ ``"2026-12-01T09:00:00+02:00"``. The client rounds it up to the
+ next millisecond and sends that time on every retry. A time at
+ or before now sends the email now. Only a client on PostHog
+ Cloud schedules.
Returns:
- The queued email. A result means PostHog queued the email, not that
- it was delivered.
+ The accepted email. A result means PostHog queued or scheduled the
+ email, not that it was delivered. ``status`` says which.
Raises:
- EmailError: PostHog did not queue the email, or the client could
- not tell whether it did.
+ EmailError: PostHog did not queue the email, the client could
+ not tell whether it did, or, with ``schedule_not_confirmed``,
+ PostHog queued it without confirming the time.
With attachments, ``code`` is ``too_many_attachments``,
``message_too_large`` or ``invalid_attachment`` before any
request, ``attachment_upload_failed`` when the storage
refused an upload, and ``network_error`` with ``field``
naming the attachment when the storage didn't answer.
- TypeError, ValueError: An argument has the wrong type or format.
+ With ``scheduled_at``, ``code`` is
+ ``scheduling_requires_cloud`` before any request when the
+ client's host isn't PostHog Cloud, and
+ ``schedule_not_confirmed`` when PostHog accepted the email
+ without confirming the time, or answered that it goes out now
+ for a time more than 60 seconds ahead of the client's clock
+ at the first attempt.
+ ``message_id`` then
+ names the email, which may go out at another time.
+ TypeError, ValueError: An argument has the wrong type or format,
+ such as a ``scheduled_at`` without a timezone.
Examples:
```python
@@ -1434,7 +1677,9 @@ def send(self, **kwargs: Any) -> SendEmailResult:
prepared = _prepare(kwargs)
finish = self._start(_SEND_NOT_DONE)
try:
- result = self._deliver(prepared, self._secret_key(_SEND_KEY_NEEDED))
+ secret_key = self._secret_key(_SEND_KEY_NEEDED)
+ self._check_schedulable(prepared)
+ result = self._deliver(prepared, secret_key)
finally:
finish()
_log_warnings(result)
@@ -1451,7 +1696,7 @@ def _deliver(self, prepared: _PreparedSend, secret_key: str) -> SendEmailResult:
)
return self._call(
self._posthog_request("POST", prepared.path, prepared.body, headers),
- _parse_response,
+ _send_parser(prepared.scheduled_at),
prepared.max_retries,
)
@@ -1653,7 +1898,9 @@ async def send(self, **kwargs: Any) -> SendEmailResult:
prepared = _prepare(kwargs)
finish = self._start(_SEND_NOT_DONE)
try:
- result = await self._deliver(prepared, self._secret_key(_SEND_KEY_NEEDED))
+ secret_key = self._secret_key(_SEND_KEY_NEEDED)
+ self._check_schedulable(prepared)
+ result = await self._deliver(prepared, secret_key)
finally:
finish()
_log_warnings(result)
@@ -1672,7 +1919,7 @@ async def _deliver(
)
return await self._call(
self._posthog_request("POST", prepared.path, prepared.body, headers),
- _parse_response,
+ _send_parser(prepared.scheduled_at),
prepared.max_retries,
)
diff --git a/posthog/test/test_emails.py b/posthog/test/test_emails.py
index 9e1a15db6..e49887b57 100644
--- a/posthog/test/test_emails.py
+++ b/posthog/test/test_emails.py
@@ -79,6 +79,17 @@ def close(self) -> None:
pass
+def on_the_wire(adapter: FakeAdapter) -> Any:
+ def send(
+ _transport: requests.adapters.HTTPAdapter,
+ request: requests.PreparedRequest,
+ **kwargs: Any,
+ ) -> requests.Response:
+ return adapter.send(request, **kwargs)
+
+ return mock.patch.object(requests.adapters.HTTPAdapter, "send", send)
+
+
def emails_with(replies: list[Reply], **options: Any) -> tuple[Emails, FakeAdapter]:
adapter = FakeAdapter(replies)
session = requests.Session()
@@ -99,6 +110,15 @@ def send(emails: Emails, **overrides: Any):
)
+NOW = datetime(2026, 11, 30, 9, tzinfo=timezone.utc)
+
+
+@pytest.fixture(autouse=True)
+def fixed_clock():
+ with mock.patch("posthog.emails._now", return_value=NOW):
+ yield
+
+
@pytest.fixture(autouse=True)
def no_sleep():
with (
@@ -568,6 +588,18 @@ def test_get_reads_the_status_of_a_sent_email_from_the_app_host():
assert "Idempotency-Key" not in request.headers
+def test_get_reads_a_status_time_with_an_offset_in_seconds():
+ emails, _adapter = emails_with(
+ [status_reply(created_at="2026-10-28T18:27:44.364000+02:00:30")]
+ )
+
+ status = emails.get(MESSAGE_ID)
+
+ assert status.created_at == datetime(
+ 2026, 10, 28, 16, 27, 14, 364000, tzinfo=timezone.utc
+ )
+
+
@parameterized.expand(
[
(
@@ -2776,3 +2808,624 @@ def test_rejects_an_attachment_it_cannot_send_without_repeating_its_content(
assert "secret-file-content" not in str(error)
assert "115, 101" not in str(error)
assert (posthog.delivered, posthog.stored_files) == ([], [])
+
+
+# Scheduled sends: scheduled_at on send, Cloud hosts only, millisecond precision, the answer checked.
+
+PLUS_TWO = timezone(timedelta(hours=2))
+DUE = "2026-12-01T09:00:00.000Z"
+
+
+def scheduled(
+ message_id: str = "msg_1", scheduled_at: Optional[str] = DUE, **fields: Any
+) -> Reply:
+ status = "scheduled" if scheduled_at is not None else "queued"
+ return accepted(
+ message_id, **{"status": status, "scheduled_at": scheduled_at, **fields}
+ )
+
+
+def sent_body(adapter: FakeAdapter, index: int = 0) -> dict[str, Any]:
+ return json.loads(adapter.requests[index].body)
+
+
+@parameterized.expand(
+ [
+ ("utc_datetime", datetime(2026, 12, 1, 9, tzinfo=timezone.utc), DUE),
+ ("offset_datetime", datetime(2026, 12, 1, 11, tzinfo=PLUS_TWO), DUE),
+ (
+ "microseconds_round_up",
+ datetime(2026, 12, 1, 9, 0, 0, 123001, tzinfo=timezone.utc),
+ "2026-12-01T09:00:00.124Z",
+ ),
+ (
+ "whole_milliseconds_stay",
+ datetime(2026, 12, 1, 9, 0, 0, 123000, tzinfo=timezone.utc),
+ "2026-12-01T09:00:00.123Z",
+ ),
+ (
+ "rounding_carries_into_the_next_day",
+ datetime(2026, 12, 31, 23, 59, 59, 999001, tzinfo=timezone.utc),
+ "2027-01-01T00:00:00.000Z",
+ ),
+ (
+ "offset_datetime_with_microseconds",
+ datetime(2026, 12, 1, 11, 0, 0, 500, tzinfo=PLUS_TWO),
+ "2026-12-01T09:00:00.001Z",
+ ),
+ ("utc_string", "2026-12-01T09:00:00Z", DUE),
+ ("offset_string", "2026-12-01T11:00:00+02:00", DUE),
+ (
+ "microsecond_string_rounds_up",
+ "2026-12-01T11:00:00.123001+02:00",
+ "2026-12-01T09:00:00.124Z",
+ ),
+ ("negative_offset_string", "2026-12-01T04:00:00.000-05:00", DUE),
+ (
+ "nanosecond_string_rounds_up",
+ "2026-12-01T11:00:00.123000001+02:00",
+ "2026-12-01T09:00:00.124Z",
+ ),
+ ("short_fraction_string", "2026-12-01T09:00:00.1Z", "2026-12-01T09:00:00.100Z"),
+ ("comma_fraction_string", "2026-12-01T09:00:00,5Z", "2026-12-01T09:00:00.500Z"),
+ ("space_separator_string", "2026-12-01 11:00:00+02:00", DUE),
+ ("minutes_only_string", "2026-12-01T11:00+02:00", DUE),
+ ]
+)
+def test_a_scheduled_send_posts_its_time_as_utc_milliseconds(_name, when, wire):
+ emails, adapter = emails_with([scheduled(scheduled_at=wire)])
+
+ result = send(emails, scheduled_at=when)
+
+ assert sent_body(adapter)["scheduled_at"] == wire
+ assert result.status == "scheduled"
+ assert result.scheduled_at == datetime.fromisoformat(wire.replace("Z", "+00:00"))
+
+
+def test_a_code_send_takes_scheduled_at_too():
+ emails, adapter = emails_with([scheduled()])
+
+ result = send_code(
+ emails, html=HTML, scheduled_at=datetime(2026, 12, 1, 9, tzinfo=timezone.utc)
+ )
+
+ assert sent_body(adapter)["scheduled_at"] == DUE
+ assert (result.status, result.scheduled_at) == (
+ "scheduled",
+ datetime(2026, 12, 1, 9, tzinfo=timezone.utc),
+ )
+
+
+def test_a_datetime_subclass_comes_back_as_the_time_on_the_wire():
+ class PreciseTime(datetime):
+ pass
+
+ emails, adapter = emails_with([scheduled(scheduled_at="2026-12-01T09:00:00.124Z")])
+ when = PreciseTime(2026, 12, 1, 9, 0, 0, 123999, tzinfo=timezone.utc)
+
+ result = send(emails, scheduled_at=when)
+
+ assert sent_body(adapter)["scheduled_at"] == "2026-12-01T09:00:00.124Z"
+ assert type(result.scheduled_at) is datetime
+ assert result.scheduled_at == datetime(
+ 2026, 12, 1, 9, 0, 0, 124000, tzinfo=timezone.utc
+ )
+
+
+@parameterized.expand(
+ [
+ ("below_a_microsecond", 1, "2026-12-01T09:00:00.124Z"),
+ ("whole_fraction_past_its_microseconds", 123000001, "2026-12-01T09:00:00.124Z"),
+ ("whole_fraction_on_a_millisecond", 123000000, "2026-12-01T09:00:00.123Z"),
+ ]
+)
+def test_a_time_with_nanoseconds_past_its_microseconds_rounds_up(
+ _name, nanoseconds, wire
+):
+ class NanosecondTime(datetime):
+ nanosecond = nanoseconds
+
+ emails, adapter = emails_with([scheduled(scheduled_at=wire)])
+ when = NanosecondTime(2026, 12, 1, 9, 0, 0, 123000, tzinfo=timezone.utc)
+
+ result = send(emails, scheduled_at=when)
+
+ assert sent_body(adapter)["scheduled_at"] == wire
+ assert result.status == "scheduled"
+
+
+@parameterized.expand([("template", send), ("code", send_code)])
+def test_scheduled_at_none_counts_as_left_out(_name, send_form):
+ emails, adapter = emails_with([accepted()])
+ extra = {"html": HTML} if send_form is send_code else {}
+
+ result = send_form(emails, scheduled_at=None, **extra)
+
+ assert "scheduled_at" not in sent_body(adapter)
+ assert (result.status, result.scheduled_at) == ("queued", None)
+
+
+def test_a_send_without_scheduled_at_keeps_todays_result():
+ emails, adapter = emails_with(
+ [accepted(status="scheduled", scheduled_at="2026-12-01T09:00:00Z")]
+ )
+
+ result = send(emails)
+
+ assert "scheduled_at" not in sent_body(adapter)
+ assert (result.id, result.status, result.scheduled_at) == ("msg_1", "queued", None)
+
+
+@parameterized.expand(
+ [
+ ("naive_datetime", datetime(2026, 12, 1, 9), ValueError, "timezone"),
+ ("string_without_offset", "2026-12-01T09:00:00", ValueError, "offset"),
+ ("date_only", "2026-12-01", ValueError, "offset"),
+ ("natural_language", "in 1 hour", ValueError, "offset"),
+ ("bad_month", "2026-13-01T09:00:00Z", ValueError, "offset"),
+ ("offset_past_a_day", "2026-12-01T09:00:00+24:00", ValueError, "offset"),
+ ("offset_minutes_past_59", "2026-12-01T09:00:00+01:60", ValueError, "offset"),
+ (
+ "offset_minutes_far_past_59",
+ "2026-12-01T09:00:00+01:99",
+ ValueError,
+ "offset",
+ ),
+ ("compact_offset_minutes", "2026-12-01T09:00:00+0160", ValueError, "offset"),
+ ("negative_offset_minutes", "2026-12-01T09:00:00-00:60", ValueError, "offset"),
+ (
+ "offset_seconds_past_59",
+ "2026-12-01T09:00:00+01:00:60",
+ ValueError,
+ "offset",
+ ),
+ (
+ "offset_with_seconds_and_fraction",
+ "2026-12-01T11:00:00+01:60:00,1",
+ ValueError,
+ "offset",
+ ),
+ ("fraction_of_an_hour", "2026-12-01T09.5+02:00", ValueError, "offset"),
+ (
+ "latest_datetime",
+ datetime.max.replace(tzinfo=timezone.utc),
+ ValueError,
+ "7 days",
+ ),
+ ("latest_time_string", "9999-12-31T23:59:59.9999Z", ValueError, "7 days"),
+ ("non_ascii_digits", "2026-12-01T09:00:00Z", ValueError, "offset"),
+ ("emoji_separator", "2026-12-01\U0001f35509:00:00Z", ValueError, "offset"),
+ ("basic_format", "20261201T090000Z", ValueError, "offset"),
+ ("hour_24", "2026-12-01T24:00:00Z", ValueError, "offset"),
+ ("lowercase_separator", "2026-12-01t09:00:00Z", ValueError, "offset"),
+ ("unix_seconds", 1796115600, TypeError, "datetime"),
+ ("date_object", datetime(2026, 12, 1).date(), TypeError, "datetime"),
+ ]
+)
+def test_refuses_a_scheduled_at_it_cannot_read_before_any_request(
+ _name, when, error, says
+):
+ emails, adapter = emails_with([])
+
+ with pytest.raises(error, match=says):
+ send(emails, scheduled_at=when)
+
+ assert adapter.requests == []
+
+
+@parameterized.expand(
+ [
+ ("custom_app_host", {"host": "https://posthog.example.com"}),
+ ("self_hosted_http", {"host": "http://localhost:8000"}),
+ ]
+)
+def test_schedules_only_on_posthog_cloud(_name, options):
+ adapter = FakeAdapter([])
+ session = requests.Session()
+ session.mount("https://", adapter)
+ session.mount("http://", adapter)
+ emails = Emails(SECRET_KEY, session=session, **options)
+
+ with pytest.raises(EmailError) as raised:
+ send(emails, scheduled_at=datetime(2026, 12, 1, 9, tzinfo=timezone.utc))
+
+ assert adapter.requests == []
+ assert raised.value.code == "scheduling_requires_cloud"
+ assert raised.value.field == "scheduled_at"
+ assert options["host"] in raised.value.message
+
+
+def test_a_scheduled_send_off_cloud_is_an_application_error():
+ adapter = FakeAdapter([])
+ session = requests.Session()
+ session.mount("https://", adapter)
+ emails = Emails(SECRET_KEY, host="https://posthog.example.com", session=session)
+
+ with pytest.raises(EmailError) as raised:
+ send(emails, scheduled_at=datetime(2026, 12, 1, 9, tzinfo=timezone.utc))
+
+ assert adapter.requests == []
+ assert (raised.value.name, raised.value.code, raised.value.field) == (
+ "application_error",
+ "scheduling_requires_cloud",
+ "scheduled_at",
+ )
+
+
+def test_a_client_with_a_custom_app_host_refuses_to_schedule_but_still_sends():
+ client = Posthog(
+ "phc_test",
+ host="https://ph.example.com",
+ secret_key=SECRET_KEY,
+ sync_mode=True,
+ app_host="https://posthog.example.com",
+ )
+
+ adapter = FakeAdapter([(202, {"message_id": "m"}, {})])
+
+ with on_the_wire(adapter):
+ with pytest.raises(EmailError) as raised:
+ send(client.emails, scheduled_at="2026-12-01T09:00:00Z")
+ assert adapter.requests == []
+ assert send(client.emails).id == "m"
+
+ assert raised.value.code == "scheduling_requires_cloud"
+ assert raised.value.message == (
+ "Scheduled sends work only on PostHog Cloud (us.posthog.com or eu.posthog.com), "
+ "and this client sends to https://posthog.example.com, so no email was sent."
+ )
+
+
+@parameterized.expand(
+ [
+ ("us", "https://us.i.posthog.com", "https://us.posthog.com/"),
+ ("eu", "https://eu.i.posthog.com", "https://eu.posthog.com/"),
+ ]
+)
+def test_a_client_on_either_cloud_region_schedules(_name, host, app_host):
+ client = Posthog("phc_test", host=host, secret_key=SECRET_KEY, sync_mode=True)
+ adapter = FakeAdapter([scheduled()])
+
+ with on_the_wire(adapter):
+ result = send(client.emails, scheduled_at="2026-12-01T09:00:00Z")
+
+ assert result.status == "scheduled"
+ assert (adapter.requests[0].url or "").startswith(app_host)
+ assert json.loads(adapter.requests[0].body)["scheduled_at"] == DUE
+
+
+def test_retries_send_the_same_time():
+ emails, adapter = emails_with(
+ [rejected(503, "delivery_unavailable"), requests.ConnectionError(), scheduled()]
+ )
+
+ send(emails, scheduled_at=datetime(2026, 12, 1, 11, tzinfo=PLUS_TWO))
+
+ bodies = [request.body for request in adapter.requests]
+ assert len(bodies) == 3 and len(set(bodies)) == 1
+ assert json.loads(bodies[0])["scheduled_at"] == DUE
+ keys = {request.headers["Idempotency-Key"] for request in adapter.requests}
+ assert len(keys) == 1
+
+
+@parameterized.expand(
+ [
+ ("same_instant_in_microseconds", "2026-12-01T09:00:00.000000Z"),
+ ("same_instant_in_another_offset", "2026-12-01T10:00:00.000+01:00"),
+ ("same_instant_without_fraction", "2026-12-01T09:00:00+00:00"),
+ ("same_instant_with_a_short_fraction", "2026-12-01T09:00:00.0Z"),
+ ]
+)
+def test_accepts_the_requested_instant_however_it_is_written(_name, answered):
+ emails, _ = emails_with([scheduled(scheduled_at=answered)])
+
+ result = send(emails, scheduled_at=DUE)
+
+ assert result.status == "scheduled"
+ assert result.scheduled_at == datetime(2026, 12, 1, 9, tzinfo=timezone.utc)
+
+
+def test_a_time_already_passed_is_an_acceptance_that_goes_out_now():
+ emails, _ = emails_with([scheduled(scheduled_at=None)])
+
+ result = send(emails, scheduled_at="2020-01-01T00:00:00Z")
+
+ assert (result.id, result.status, result.scheduled_at) == ("msg_1", "queued", None)
+
+
+@parameterized.expand(
+ [
+ (
+ "null_time_over_a_minute_ahead",
+ {"status": "queued", "scheduled_at": None},
+ 61,
+ ),
+ ("no_time_over_a_minute_ahead", {"status": "queued"}, 61),
+ ("no_time_within_a_minute", {"status": "queued"}, 30),
+ ]
+)
+def test_a_send_now_answer_for_a_time_over_a_minute_ahead_is_not_confirmed(
+ _name, fields, ahead
+):
+ emails, adapter = emails_with([accepted("msg_9", **fields)])
+
+ with pytest.raises(EmailError) as raised:
+ send(emails, scheduled_at=NOW + timedelta(seconds=ahead))
+
+ assert len(adapter.requests) == 1
+ assert (raised.value.code, raised.value.message_id) == (
+ "schedule_not_confirmed",
+ "msg_9",
+ )
+
+
+@parameterized.expand(
+ [
+ ("null_time", {"status": "queued", "scheduled_at": None}, 60),
+ ("null_time_already_passed", {"status": "queued", "scheduled_at": None}, -60),
+ ]
+)
+def test_a_send_now_answer_within_a_minute_goes_out_now(_name, fields, ahead):
+ emails, _ = emails_with([accepted("msg_9", **fields)])
+
+ result = send(emails, scheduled_at=NOW + timedelta(seconds=ahead))
+
+ assert (result.id, result.status, result.scheduled_at) == ("msg_9", "queued", None)
+
+
+class MovingClock:
+ def __init__(self) -> None:
+ self.now = NOW
+
+ def advance(self, seconds: float) -> None:
+ self.now += timedelta(seconds=seconds)
+
+
+@contextmanager
+def moving_clock():
+ clock = MovingClock()
+ with mock.patch("posthog.emails._now", side_effect=lambda: clock.now):
+ yield clock
+
+
+class SlowAdapter(FakeAdapter):
+ def __init__(
+ self, replies: list[Reply], clock: MovingClock, seconds: float
+ ) -> None:
+ super().__init__(replies)
+ self.clock = clock
+ self.seconds = seconds
+
+ def send(
+ self, request: requests.PreparedRequest, **kwargs: Any
+ ) -> requests.Response:
+ self.clock.advance(self.seconds)
+ return super().send(request, **kwargs)
+
+
+def emails_on_a_slow_line(
+ replies: list[Reply], clock: MovingClock, seconds: float
+) -> Emails:
+ session = requests.Session()
+ session.mount("https://", SlowAdapter(replies, clock, seconds))
+ return Emails(SECRET_KEY, session=session)
+
+
+def test_a_send_now_answer_counts_from_the_first_attempt_not_the_answer():
+ with moving_clock() as clock:
+ emails = emails_on_a_slow_line(
+ [accepted("msg_9", status="queued", scheduled_at=None)], clock, 3
+ )
+
+ with pytest.raises(EmailError) as raised:
+ send(emails, scheduled_at=NOW + timedelta(seconds=62))
+
+ assert (raised.value.code, raised.value.message_id) == (
+ "schedule_not_confirmed",
+ "msg_9",
+ )
+
+
+def test_a_send_now_answer_after_a_retry_counts_from_the_first_attempt(no_sleep):
+ with moving_clock() as clock:
+ no_sleep.side_effect = lambda _seconds: clock.advance(30)
+ emails, adapter = emails_with(
+ [
+ rejected(503, "delivery_unavailable"),
+ accepted("msg_9", status="queued", scheduled_at=None),
+ ]
+ )
+
+ result = send(emails, scheduled_at=NOW + timedelta(seconds=58))
+
+ assert len(adapter.requests) == 2
+ assert (result.id, result.status, result.scheduled_at) == ("msg_9", "queued", None)
+
+
+def test_a_retry_does_not_restart_the_send_now_window(no_sleep):
+ with moving_clock() as clock:
+ no_sleep.side_effect = lambda _seconds: clock.advance(30)
+ emails, adapter = emails_with(
+ [
+ rejected(503, "delivery_unavailable"),
+ accepted("msg_9", status="queued", scheduled_at=None),
+ ]
+ )
+
+ with pytest.raises(EmailError) as raised:
+ send(emails, scheduled_at=NOW + timedelta(seconds=62))
+
+ assert len(adapter.requests) == 2
+ assert (raised.value.code, raised.value.message_id) == (
+ "schedule_not_confirmed",
+ "msg_9",
+ )
+
+
+@pytest.mark.asyncio
+async def test_async_send_now_answer_counts_from_the_first_attempt_not_the_answer():
+ with moving_clock() as clock:
+
+ def handler(_request: httpx.Request) -> httpx.Response:
+ clock.advance(3)
+ return httpx.Response(
+ 202,
+ json={"message_id": "msg_9", "status": "queued", "scheduled_at": None},
+ )
+
+ emails = AsyncEmails(
+ SECRET_KEY,
+ http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)),
+ )
+
+ with pytest.raises(EmailError) as raised:
+ await emails.send(
+ to="user@example.com",
+ template_id=TEMPLATE_ID,
+ scheduled_at=NOW + timedelta(seconds=62),
+ )
+
+ assert raised.value.code == "schedule_not_confirmed"
+
+
+@parameterized.expand(
+ [
+ ("nothing_but_the_id", {}),
+ (
+ "another_instant",
+ {"status": "scheduled", "scheduled_at": "2026-12-01T09:00:00.001Z"},
+ ),
+ ("scheduled_without_a_time", {"status": "scheduled", "scheduled_at": None}),
+ ("queued_with_a_time", {"status": "queued", "scheduled_at": DUE}),
+ ("no_status", {"scheduled_at": DUE}),
+ ("unreadable_time", {"status": "scheduled", "scheduled_at": "soon"}),
+ (
+ "offset_minutes_past_59",
+ {"status": "scheduled", "scheduled_at": "2026-12-01T10:00:00+00:60"},
+ ),
+ ("null_time_without_status", {"scheduled_at": None}),
+ ]
+)
+def test_raises_when_posthog_does_not_confirm_the_schedule(_name, fields):
+ emails, adapter = emails_with([accepted("msg_9", **fields)])
+
+ with pytest.raises(EmailError) as raised:
+ send(emails, scheduled_at=DUE)
+
+ assert len(adapter.requests) == 1 # a retry would only replay the same answer
+ error = raised.value
+ assert error.code == "schedule_not_confirmed"
+ assert error.status_code == 202
+ assert error.message_id == "msg_9"
+ assert "msg_9" in error.message
+
+
+def test_a_refused_scheduled_at_raises_and_never_sends_now():
+ emails, adapter = emails_with(
+ [
+ (
+ 400,
+ {
+ "type": "validation_error",
+ "code": "invalid_input",
+ "detail": "scheduled_at must be within 7 days.",
+ "attr": "scheduled_at",
+ },
+ {},
+ )
+ ]
+ )
+
+ with pytest.raises(EmailError) as raised:
+ send(emails, scheduled_at="2026-12-30T09:00:00Z")
+
+ assert len(adapter.requests) == 1
+ assert (raised.value.status_code, raised.value.field) == (400, "scheduled_at")
+
+
+def async_emails_with(
+ replies: list[httpx.Response], **options: Any
+) -> tuple[AsyncEmails, list[httpx.Request]]:
+ seen: list[httpx.Request] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ seen.append(request)
+ return replies.pop(0)
+
+ client = httpx.AsyncClient(transport=httpx.MockTransport(handler))
+ return AsyncEmails(SECRET_KEY, http_client=client, **options), seen
+
+
+@pytest.mark.asyncio
+async def test_async_retries_send_the_same_rounded_time_and_confirm_it():
+ emails, seen = async_emails_with(
+ [
+ httpx.Response(503, json={"code": "delivery_unavailable"}),
+ httpx.Response(
+ 202,
+ json={
+ "message_id": "msg_1",
+ "status": "scheduled",
+ "scheduled_at": "2026-12-01T09:00:00.001Z",
+ },
+ ),
+ ]
+ )
+
+ with mock.patch("posthog.emails.asyncio.sleep"):
+ result = await emails.send(
+ to="user@example.com",
+ template_id=TEMPLATE_ID,
+ scheduled_at=datetime(2026, 12, 1, 11, 0, 0, 999, tzinfo=PLUS_TWO),
+ )
+
+ assert [request.content for request in seen] == [seen[0].content] * 2
+ assert json.loads(seen[0].content)["scheduled_at"] == "2026-12-01T09:00:00.001Z"
+ assert (result.status, result.scheduled_at) == (
+ "scheduled",
+ datetime(2026, 12, 1, 9, 0, 0, 1000, tzinfo=timezone.utc),
+ )
+
+
+@pytest.mark.asyncio
+async def test_async_raises_when_posthog_does_not_confirm_the_time():
+ emails, _ = async_emails_with([httpx.Response(202, json={"message_id": "msg_2"})])
+
+ with pytest.raises(EmailError) as unconfirmed:
+ await emails.send(
+ to="user@example.com",
+ template_key="welcome",
+ subject="Hi",
+ html=HTML,
+ scheduled_at=DUE,
+ )
+
+ assert unconfirmed.value.code == "schedule_not_confirmed"
+ assert unconfirmed.value.message_id == "msg_2"
+
+
+@pytest.mark.asyncio
+async def test_async_refuses_a_custom_host_before_any_request():
+ emails, seen = async_emails_with([], host="https://posthog.example.com")
+
+ with pytest.raises(EmailError) as off_cloud:
+ await emails.send(
+ to="user@example.com", template_id=TEMPLATE_ID, scheduled_at=DUE
+ )
+
+ assert off_cloud.value.code == "scheduling_requires_cloud"
+ assert seen == []
+
+
+@pytest.mark.asyncio
+async def test_async_refuses_a_naive_time_before_any_request():
+ emails, seen = async_emails_with([])
+
+ with pytest.raises(ValueError):
+ await emails.send(
+ to="user@example.com",
+ template_id=TEMPLATE_ID,
+ scheduled_at=datetime(2026, 12, 1),
+ )
+
+ assert seen == []
diff --git a/references/public_api_snapshot.txt b/references/public_api_snapshot.txt
index 9891e9fa5..d3fbb7bb8 100644
--- a/references/public_api_snapshot.txt
+++ b/references/public_api_snapshot.txt
@@ -941,6 +941,7 @@ attribute posthog.emails.EmailError.docs_url = docs_url
attribute posthog.emails.EmailError.field = field
attribute posthog.emails.EmailError.fix = fix
attribute posthog.emails.EmailError.message = message
+attribute posthog.emails.EmailError.message_id = message_id
attribute posthog.emails.EmailError.name = name
attribute posthog.emails.EmailError.retry_after = retry_after
attribute posthog.emails.EmailError.status_code = status_code
@@ -958,6 +959,8 @@ attribute posthog.emails.EmailWarning.fix: Optional[str] = None
attribute posthog.emails.EmailWarning.message: str
attribute posthog.emails.SendEmailResult.id: str
attribute posthog.emails.SendEmailResult.replayed: bool = False
+attribute posthog.emails.SendEmailResult.scheduled_at: Optional[datetime] = None
+attribute posthog.emails.SendEmailResult.status: Literal['queued', 'scheduled']
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]
@@ -1400,12 +1403,12 @@ class posthog.contexts.ContextScope(parent=None, fresh: bool = False, capture_ex
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, migrated_from: Optional[str] = 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.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, message_id: Optional[str] = None)
class posthog.emails.EmailStatus(id: str, status: str, created_at: datetime, status_at: datetime, reason: Optional[str] = None)
class posthog.emails.EmailTracking
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, migrated_from: Optional[str] = None)
-class posthog.emails.SendEmailResult(id: str, replayed: bool = False, warnings: tuple[EmailWarning, ...] = ())
+class posthog.emails.SendEmailResult(id: str, replayed: bool = False, warnings: tuple[EmailWarning, ...] = (), scheduled_at: Optional[datetime] = None)
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)