Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement mailtrap import source (#69352)

Tom Owers8752f2cc2f2f
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 41b9fd55a561..3bfe1f74f6c9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -232,6 +232,7 @@ the row lists both.
| mailgun | HTTP | requests | ✅ |
| mailjet | HTTP | requests | ✅ |
| mailosaur | HTTP | requests | ✅ |
+| mailtrap | HTTP | requests | ✅ |
| marketstack | HTTP | requests | ✅ |
| matomo | HTTP | requests | ✅ |
| mention | HTTP | requests | ✅ |
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 5aca3bd25e38..e6b194039565 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -2051,7 +2051,7 @@ class MailosaurSourceConfig(config.Config):
@config.config
class MailtrapSourceConfig(config.Config):
- pass
+ api_token: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/canonical_descriptions.py
new file mode 100644
index 000000000000..c2deed9b4f47
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/canonical_descriptions.py
@@ -0,0 +1,93 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the Mailtrap API docs (https://docs.mailtrap.io/developers).
+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "email_logs": {
+ "description": "A sent email's delivery log entry, covering both the transactional and bulk sending streams.",
+ "docs_url": "https://docs.mailtrap.io/developers/email-sending/email-logs",
+ "columns": {
+ "message_id": "The unique UUID of the sent message.",
+ "status": "Delivery status of the message (delivered, not_delivered, enqueued, or opted_out).",
+ "subject": "The email subject line.",
+ "from": "The sender email address.",
+ "to": "The recipient email address.",
+ "sent_at": "When the message was sent.",
+ "client_ip": "IP address of the client that submitted the message.",
+ "category": "The sender-assigned category of the message.",
+ "custom_variables": "Custom variables attached to the message at send time.",
+ "sending_stream": "Which sending stream carried the message (transactional or bulk).",
+ "domain_id": "The ID of the sending domain the message was sent from.",
+ "template_id": "The ID of the email template used, if any.",
+ "template_variables": "Template variables supplied at send time, if a template was used.",
+ "opens_count": "Number of times the message was opened.",
+ "clicks_count": "Number of link clicks recorded for the message.",
+ },
+ },
+ "suppressions": {
+ "description": "A suppressed recipient email address that will not receive emails from your account.",
+ "docs_url": "https://docs.mailtrap.io/developers/email-sending/suppressions",
+ "columns": {
+ "id": "The unique UUID of the suppression.",
+ "type": "Reason for the suppression (hard bounce, unsubscription, spam complaint, or manual import).",
+ "created_at": "When the suppression was created.",
+ "email": "The suppressed email address.",
+ "sending_stream": "Which sending stream the suppression applies to (transactional, bulk, or any).",
+ "domain_name": "The sending domain the suppression is associated with.",
+ "message_bounce_category": "Bounce category of the message that triggered the suppression.",
+ "message_category": "Sender-assigned category of the triggering message.",
+ "message_client_ip": "IP address of the client that submitted the triggering message.",
+ "message_created_at": "When the triggering message was created.",
+ "message_esp_response": "The receiving email service provider's response for the triggering message.",
+ "message_esp_server_type": "The receiving email service provider's server type.",
+ "message_outgoing_ip": "The IP address the triggering message was sent from.",
+ "message_recipient_mx_name": "The recipient's MX server name.",
+ "message_sender_email": "Sender address of the triggering message.",
+ "message_subject": "Subject of the triggering message.",
+ },
+ },
+ "email_templates": {
+ "description": "A reusable email template with dynamic content.",
+ "docs_url": "https://docs.mailtrap.io/developers/templates/templates",
+ "columns": {
+ "id": "The unique ID of the template.",
+ "uuid": "The UUID of the template, used when sending emails from it.",
+ "name": "The template name.",
+ "category": "The template category.",
+ "subject": "The email subject line the template renders.",
+ "body_text": "The plain-text body of the template.",
+ "body_html": "The HTML body of the template.",
+ "created_at": "When the template was created.",
+ "updated_at": "When the template was last updated.",
+ },
+ },
+ "contact_lists": {
+ "description": "A named list used to group marketing contacts.",
+ "docs_url": "https://docs.mailtrap.io/developers/promotional/contacts/contact-lists",
+ "columns": {
+ "id": "The unique ID of the contact list.",
+ "name": "The contact list name.",
+ },
+ },
+ "sending_domains": {
+ "description": "A domain configured for sending emails, with its compliance and DNS verification state.",
+ "docs_url": "https://docs.mailtrap.io/developers/email-sending/domains",
+ "columns": {
+ "id": "The unique ID of the sending domain.",
+ "domain_name": "The domain name.",
+ "demo": "Whether this is a Mailtrap-provided demo domain.",
+ "compliance_status": "The domain's compliance verification status; it must be compliant before production sending.",
+ },
+ },
+ "accounts": {
+ "description": "A Mailtrap account the API token has access to.",
+ "docs_url": "https://docs.mailtrap.io/developers/account-management/accounts",
+ "columns": {
+ "id": "The unique ID of the account.",
+ "name": "The account name.",
+ "access_levels": "The token's access levels on the account (1000 owner, 100 admin, 10 viewer).",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/mailtrap.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/mailtrap.py
new file mode 100644
index 000000000000..26e834935bac
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/mailtrap.py
@@ -0,0 +1,204 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import date, datetime
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.mailtrap.settings import (
+ MAILTRAP_ENDPOINTS,
+ MailtrapEndpointConfig,
+)
+
+# Management/logs host. Sending hosts (send.api.mailtrap.io, bulk.api.mailtrap.io) are write-only
+# and never used by this connector.
+MAILTRAP_BASE_URL = "https://mailtrap.io"
+REQUEST_TIMEOUT_SECONDS = 60
+# Cheap probe to confirm a token is genuine: every token can list the accounts it has access to.
+DEFAULT_PROBE_PATH = "/api/accounts"
+
+
+class MailtrapRetryableError(Exception):
+ pass
+
+
+class MailtrapResumeConfig:
+ # Opaque cursor for the next page: `next_page_cursor` for email_logs, the last suppression's
+ # UUID for suppressions. A crashed sync resumes from the page after the last one yielded; merge
+ # dedupes the re-pulled page on the primary key. `None` means start from the first page.
+ cursor: str | None = None
+
+
+def _headers(api_token: str) -> dict[str, str]:
+ return {"Api-Token": api_token, "Accept": "application/json"}
+
+
+def _format_timestamp(value: Any) -> str:
+ if isinstance(value, datetime | date):
+ return value.isoformat()
+ return str(value)
+
+
+@retry(
+ retry=retry_if_exception_type((MailtrapRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ path: str,
+ params: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> Any:
+ response = session.get(f"{MAILTRAP_BASE_URL}{path}", params=params, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # Mailtrap rate limits per token (and per account for suppressions); 429s are retried with
+ # backoff alongside transient 5xx.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise MailtrapRetryableError(f"Mailtrap API error (retryable): status={response.status_code}, path={path}")
+
+ if not response.ok:
+ logger.error(f"Mailtrap API error: status={response.status_code}, body={response.text}, path={path}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _extract_rows(config: MailtrapEndpointConfig, data: Any, path: str) -> list[dict[str, Any]]:
+ if config.data_key is not None:
+ if not isinstance(data, dict) or not isinstance(data.get(config.data_key), list):
+ raise MailtrapRetryableError(f"Mailtrap returned an unexpected payload for {path}: {type(data).__name__}")
+ return data[config.data_key]
+
+ if not isinstance(data, list):
+ raise MailtrapRetryableError(f"Mailtrap returned an unexpected payload for {path}: {type(data).__name__}")
+ return data
+
+
+def _next_cursor(config: MailtrapEndpointConfig, data: Any, rows: list[dict[str, Any]]) -> Optional[str]:
+ if config.cursor_param is None or not rows:
+ return None
+
+ if config.cursor_response_key is not None:
+ cursor = data.get(config.cursor_response_key) if isinstance(data, dict) else None
+ return str(cursor) if cursor else None
+
+ if config.cursor_row_field is not None:
+ # No explicit next-page signal: a full page means there may be more rows after the last id.
+ if config.page_size is not None and len(rows) < config.page_size:
+ return None
+ cursor = rows[-1][config.cursor_row_field]
+ return str(cursor) if cursor is not None else None
+
+ return None
+
+
+def get_rows(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[MailtrapResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = MAILTRAP_ENDPOINTS[endpoint]
+ session = make_tracked_session(headers=_headers(api_token), redact_values=(api_token,))
+
+ base_params: dict[str, Any] = {}
+ if config.incremental_param and should_use_incremental_field and db_incremental_field_last_value is not None:
+ # Server-side lower bound (filters[sent_after] / start_time) is re-sent on every page so
+ # cursor pagination never walks past the watermark into already-synced history.
+ base_params[config.incremental_param] = _format_timestamp(db_incremental_field_last_value)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ cursor = resume.cursor if resume else None
+ if cursor is not None:
+ logger.debug(f"Mailtrap: resuming {endpoint} from cursor {cursor}")
+
+ while True:
+ params = dict(base_params)
+ if cursor is not None and config.cursor_param is not None:
+ params[config.cursor_param] = cursor
+
+ data = _fetch_page(session, config.path, params, logger)
+ rows = _extract_rows(config, data, config.path)
+ if rows:
+ yield rows
+
+ cursor = _next_cursor(config, data, rows)
+ if cursor is None:
+ break
+
+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are
+ # persisted); merge dedupes the re-pulled page on the primary key.
+ resumable_source_manager.save_state(MailtrapResumeConfig(cursor=cursor))
+
+
+def mailtrap_source(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[MailtrapResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> SourceResponse:
+ config = MAILTRAP_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_token=api_token,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ # email_logs is documented newest-first; suppressions ordering is undocumented. "desc" makes
+ # the pipeline commit the incremental watermark only after a sync completes, which is safe
+ # in both cases.
+ sort_mode="desc" if config.incremental_param else "asc",
+ )
+
+
+def check_access(api_token: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:
+ """Probe a single endpoint to validate the API token.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a
+ connection problem, other HTTP status otherwise.
+ """
+ session = make_tracked_session(headers=_headers(api_token), redact_values=(api_token,))
+ try:
+ response = session.get(f"{MAILTRAP_BASE_URL}{path}", timeout=15)
+ except Exception as e:
+ return 0, f"Could not connect to Mailtrap: {e}"
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"Mailtrap returned HTTP {response.status_code}"
+
+ return 200, None
+
+
+def validate_credentials(api_token: str) -> tuple[bool, str | None]:
+ status, message = check_access(api_token)
+ if status == 200:
+ return True, None
+ if status in (401, 403):
+ return False, "Invalid Mailtrap API token"
+ return False, message or "Could not validate Mailtrap API token"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/settings.py
new file mode 100644
index 000000000000..0a0b91c75fe9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/settings.py
@@ -0,0 +1,86 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class MailtrapEndpointConfig:
+ name: str
+ path: str
+ # Key wrapping the rows in the response body; None means the body is a bare JSON array.
+ data_key: Optional[str] = None
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Cursor query param for paginated endpoints (None = single-request endpoint).
+ cursor_param: Optional[str] = None
+ # Where the next cursor comes from: a top-level response field, or the last row's field.
+ cursor_response_key: Optional[str] = None
+ cursor_row_field: Optional[str] = None
+ # Page size the API caps responses at; used to detect the last page when the API exposes no
+ # explicit next-page signal (suppressions).
+ page_size: Optional[int] = None
+ # Server-side lower-bound timestamp query param for incremental syncs.
+ incremental_param: Optional[str] = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable datetime field used for partitioning (creation/send time, never an updated_at).
+ partition_key: Optional[str] = None
+
+
+# Mailtrap REST API list endpoints (https://mailtrap.io/api, Api-Token header auth). All paths are
+# token-scoped: results cover every account/domain the token can access, so no account_id is needed.
+#
+# Incremental sync:
+# - email_logs exposes a server-side `filters[sent_after]` bound and cursor pagination via
+# `search_after`/`next_page_cursor`; results are ordered by sent_at descending.
+# - suppressions exposes a server-side `start_time` (created-at) bound and `last_id` cursor
+# pagination, capped at 1000 rows per request.
+# Both are declared sort_mode="desc" so the incremental watermark only commits once a sync
+# completes (suppressions ordering is undocumented; email logs are documented newest-first).
+# The remaining endpoints return unpaginated arrays with no timestamp filter: full refresh only.
+MAILTRAP_ENDPOINTS: dict[str, MailtrapEndpointConfig] = {
+ "email_logs": MailtrapEndpointConfig(
+ name="email_logs",
+ path="/api/email_logs",
+ data_key="messages",
+ primary_keys=["message_id"],
+ cursor_param="search_after",
+ cursor_response_key="next_page_cursor",
+ incremental_param="filters[sent_after]",
+ incremental_fields=[
+ {
+ "label": "sent_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "sent_at",
+ "field_type": IncrementalFieldType.DateTime,
+ }
+ ],
+ partition_key="sent_at",
+ ),
+ "suppressions": MailtrapEndpointConfig(
+ name="suppressions",
+ path="/api/suppressions",
+ cursor_param="last_id",
+ cursor_row_field="id",
+ page_size=1000,
+ incremental_param="start_time",
+ incremental_fields=[
+ {
+ "label": "created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at",
+ "field_type": IncrementalFieldType.DateTime,
+ }
+ ],
+ partition_key="created_at",
+ ),
+ "email_templates": MailtrapEndpointConfig(name="email_templates", path="/api/email_templates"),
+ "contact_lists": MailtrapEndpointConfig(name="contact_lists", path="/api/contacts/lists"),
+ "sending_domains": MailtrapEndpointConfig(name="sending_domains", path="/api/domains", data_key="data"),
+ "accounts": MailtrapEndpointConfig(name="accounts", path="/api/accounts"),
+}
+
+ENDPOINTS = tuple(MAILTRAP_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ endpoint: config.incremental_fields for endpoint, config in MAILTRAP_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/source.py
index 7b174de430b5..4638443490fb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/source.py
@@ -1,19 +1,43 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import MailtrapSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.mailtrap.mailtrap import (
+ MailtrapResumeConfig,
+ mailtrap_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.mailtrap.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ MAILTRAP_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class MailtrapSource(SimpleSource[MailtrapSourceConfig]):
+class MailtrapSource(ResumableSource[MailtrapSourceConfig, MailtrapResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.MAILTRAP
@@ -22,9 +46,95 @@ class MailtrapSource(SimpleSource[MailtrapSourceConfig]):
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.MAILTRAP,
- category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
+ category=DataWarehouseSourceCategory.MARKETING___EMAIL,
label="Mailtrap",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Mailtrap API token to pull your email sending data into the PostHog Data warehouse.
+
+You can create an API token under **Settings → API Tokens** in [Mailtrap](https://mailtrap.io). The token needs access to the accounts and sending domains you want to sync; email logs are restricted to the domains the token can access.
+""",
iconPath="/static/services/mailtrap.png",
- fields=cast(list[FieldType], []),
+ docsUrl="https://posthog.com/docs/cdp/sources/mailtrap",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
unreleasedSource=True,
)
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.mailtrap.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://mailtrap.io": "Your Mailtrap API token is invalid or has been revoked. Create a new token under Settings → API Tokens, then reconnect.",
+ "403 Client Error: Forbidden for url: https://mailtrap.io": "Your Mailtrap API token does not have access to this data. Check the token's account and domain permissions, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: MailtrapSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ # Only email_logs (filters[sent_after]) and suppressions (start_time) expose a
+ # server-side timestamp bound; the other endpoints are unpaginated full-refresh lists.
+ incremental_fields = INCREMENTAL_FIELDS.get(endpoint, [])
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=len(incremental_fields) > 0,
+ supports_append=len(incremental_fields) > 0,
+ incremental_fields=incremental_fields,
+ )
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: MailtrapSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # One cheap probe (/api/accounts) confirms the token is genuine; every token can list the
+ # accounts it has access to.
+ return validate_credentials(config.api_token)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MailtrapResumeConfig]:
+ return ResumableSourceManager[MailtrapResumeConfig](inputs, MailtrapResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: MailtrapSourceConfig,
+ resumable_source_manager: ResumableSourceManager[MailtrapResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in MAILTRAP_ENDPOINTS:
+ raise ValueError(f"Unknown Mailtrap schema '{inputs.schema_name}'")
+
+ return mailtrap_source(
+ api_token=config.api_token,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/tests/test_mailtrap.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/tests/test_mailtrap.py
new file mode 100644
index 000000000000..059a0016663b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/tests/test_mailtrap.py
@@ -0,0 +1,331 @@
+from collections.abc import Callable
+from typing import Any, Optional
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.mailtrap import mailtrap
+from products.warehouse_sources.backend.temporal.data_imports.sources.mailtrap.mailtrap import (
+ MAILTRAP_BASE_URL,
+ MailtrapResumeConfig,
+ MailtrapRetryableError,
+ check_access,
+ get_rows,
+ mailtrap_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.mailtrap.settings import (
+ ENDPOINTS,
+ MAILTRAP_ENDPOINTS,
+)
+
+# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.
+_fetch_page_unwrapped = mailtrap._fetch_page.__wrapped__ # type: ignore[attr-defined]
+
+FetchFn = Callable[..., Any]
+
+
+class _FakeResumableManager:
+ def __init__(self, state: MailtrapResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[MailtrapResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> MailtrapResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: MailtrapResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _collect(
+ manager: _FakeResumableManager,
+ fetch: FetchFn,
+ endpoint: str,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> list[dict]:
+ monkeypatch = pytest.MonkeyPatch()
+ try:
+ monkeypatch.setattr(mailtrap, "_fetch_page", fetch)
+ monkeypatch.setattr(mailtrap, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ api_token="token",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ):
+ rows.extend(batch)
+ return rows
+ finally:
+ monkeypatch.undo()
+
+
+class TestGetRows:
+ def test_email_logs_follows_next_page_cursor_until_null(self) -> None:
+ manager = _FakeResumableManager()
+ pages = {
+ None: {"messages": [{"message_id": "m1"}], "next_page_cursor": "c2", "total_count": 2},
+ "c2": {"messages": [{"message_id": "m2"}], "next_page_cursor": None, "total_count": 2},
+ }
+
+ def fetch(session: Any, path: str, params: dict, logger: Any) -> Any:
+ return pages[params.get("search_after")]
+
+ rows = _collect(manager, fetch, "email_logs")
+ assert rows == [{"message_id": "m1"}, {"message_id": "m2"}]
+ # State is saved once — after the first page, pointing at the next cursor — then we stop.
+ assert [s.cursor for s in manager.saved] == ["c2"]
+
+ def test_email_logs_incremental_sends_sent_after_on_every_page(self) -> None:
+ manager = _FakeResumableManager()
+ seen_params: list[dict] = []
+ pages = {
+ None: {"messages": [{"message_id": "m1"}], "next_page_cursor": "c2"},
+ "c2": {"messages": [{"message_id": "m2"}], "next_page_cursor": None},
+ }
+
+ def fetch(session: Any, path: str, params: dict, logger: Any) -> Any:
+ seen_params.append(params)
+ return pages[params.get("search_after")]
+
+ _collect(
+ manager,
+ fetch,
+ "email_logs",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-01-01T00:00:00Z",
+ )
+ # The server-side bound must ride along with the cursor, or later pages walk unbounded
+ # through already-synced history.
+ assert len(seen_params) == 2
+ assert all(p.get("filters[sent_after]") == "2026-01-01T00:00:00Z" for p in seen_params)
+
+ def test_email_logs_full_refresh_sends_no_time_filter(self) -> None:
+ manager = _FakeResumableManager()
+ seen_params: list[dict] = []
+
+ def fetch(session: Any, path: str, params: dict, logger: Any) -> Any:
+ seen_params.append(params)
+ return {"messages": [{"message_id": "m1"}], "next_page_cursor": None}
+
+ _collect(manager, fetch, "email_logs")
+ assert "filters[sent_after]" not in seen_params[0]
+
+ def test_email_logs_resumes_from_saved_cursor(self) -> None:
+ manager = _FakeResumableManager(MailtrapResumeConfig(cursor="c2"))
+ seen_cursors: list[Optional[str]] = []
+
+ def fetch(session: Any, path: str, params: dict, logger: Any) -> Any:
+ seen_cursors.append(params.get("search_after"))
+ return {"messages": [{"message_id": "m2"}], "next_page_cursor": None}
+
+ rows = _collect(manager, fetch, "email_logs")
+ assert rows == [{"message_id": "m2"}]
+ # The first page must never be re-fetched on resume.
+ assert seen_cursors == ["c2"]
+
+ def test_suppressions_paginates_by_last_row_id_until_short_page(self) -> None:
+ manager = _FakeResumableManager()
+ page_size = MAILTRAP_ENDPOINTS["suppressions"].page_size
+ assert page_size is not None
+ full_page = [{"id": f"s{i}"} for i in range(page_size)]
+ short_page = [{"id": "last"}]
+
+ def fetch(session: Any, path: str, params: dict, logger: Any) -> Any:
+ return short_page if params.get("last_id") == full_page[-1]["id"] else full_page
+
+ rows = _collect(manager, fetch, "suppressions")
+ assert len(rows) == page_size + 1
+ # The cursor advances from the last row of the full page; the short page ends the sync.
+ assert [s.cursor for s in manager.saved] == [full_page[-1]["id"]]
+
+ def test_suppressions_incremental_sends_start_time(self) -> None:
+ manager = _FakeResumableManager()
+ seen_params: list[dict] = []
+
+ def fetch(session: Any, path: str, params: dict, logger: Any) -> Any:
+ seen_params.append(params)
+ return [{"id": "s1"}]
+
+ _collect(
+ manager,
+ fetch,
+ "suppressions",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-01-01T00:00:00Z",
+ )
+ assert seen_params[0]["start_time"] == "2026-01-01T00:00:00Z"
+
+ def test_empty_first_page_yields_nothing(self) -> None:
+ manager = _FakeResumableManager()
+
+ def fetch(session: Any, path: str, params: dict, logger: Any) -> Any:
+ return {"messages": [], "next_page_cursor": None}
+
+ rows = _collect(manager, fetch, "email_logs")
+ assert rows == []
+ assert manager.saved == []
+
+ @parameterized.expand(
+ [
+ ("email_templates", [{"id": 1}]),
+ ("contact_lists", [{"id": 2, "name": "list"}]),
+ ("accounts", [{"id": 3, "name": "acct"}]),
+ ]
+ )
+ def test_unpaginated_bare_array_endpoints_fetch_once(self, endpoint: str, body: list[dict]) -> None:
+ manager = _FakeResumableManager()
+ calls: list[dict] = []
+
+ def fetch(session: Any, path: str, params: dict, logger: Any) -> Any:
+ calls.append(params)
+ return body
+
+ rows = _collect(manager, fetch, endpoint)
+ assert rows == body
+ assert len(calls) == 1
+ assert manager.saved == []
+
+ def test_sending_domains_unwraps_data_key(self) -> None:
+ manager = _FakeResumableManager()
+
+ def fetch(session: Any, path: str, params: dict, logger: Any) -> Any:
+ return {"data": [{"id": 1, "domain_name": "example.com"}]}
+
+ rows = _collect(manager, fetch, "sending_domains")
+ assert rows == [{"id": 1, "domain_name": "example.com"}]
+
+ @parameterized.expand(
+ [
+ ("email_logs_bare_list", "email_logs", [{"message_id": "m1"}]),
+ ("email_logs_missing_key", "email_logs", {"total_count": 0}),
+ ("templates_wrapped", "email_templates", {"data": []}),
+ ]
+ )
+ def test_unexpected_payload_is_retryable(self, _name: str, endpoint: str, body: Any) -> None:
+ manager = _FakeResumableManager()
+ with pytest.raises(MailtrapRetryableError):
+ _collect(manager, lambda *args, **kwargs: body, endpoint)
+
+
+class TestFetchPage:
+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body if body is not None else []
+ response.text = ""
+ response.raise_for_status.side_effect = (
+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None
+ )
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(MailtrapRetryableError):
+ _fetch_page_unwrapped(session, "/api/email_logs", {}, MagicMock())
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(requests.HTTPError):
+ _fetch_page_unwrapped(session, "/api/email_logs", {}, MagicMock())
+
+ def test_success_returns_body_and_sends_params(self) -> None:
+ body = {"messages": [{"message_id": "m1"}], "next_page_cursor": None}
+ session = self._session_returning(200, body)
+ params = {"search_after": "c2", "filters[sent_after]": "2026-01-01T00:00:00Z"}
+ assert _fetch_page_unwrapped(session, "/api/email_logs", params, MagicMock()) == body
+ args, kwargs = session.get.call_args
+ assert args[0] == f"{MAILTRAP_BASE_URL}/api/email_logs"
+ assert kwargs["params"] == params
+
+
+class TestCheckAccess:
+ def _session(self, response: Any) -> MagicMock:
+ session = MagicMock()
+ if isinstance(response, Exception):
+ session.get.side_effect = response
+ else:
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, 200, None),
+ ("unauthorized", 401, False, 401, None),
+ ("forbidden", 403, False, 403, None),
+ ("server_error", 500, False, 500, "Mailtrap returned HTTP 500"),
+ ]
+ )
+ def test_status_mapping(
+ self, _name: str, status: int, ok: bool, expected_status: int, expected_message: str | None
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = ok
+ with patch.object(mailtrap, "make_tracked_session", return_value=self._session(response)):
+ assert check_access("token") == (expected_status, expected_message)
+
+ def test_connection_error_maps_to_zero(self) -> None:
+ session = self._session(requests.ConnectionError("boom"))
+ with patch.object(mailtrap, "make_tracked_session", return_value=session):
+ status, message = check_access("token")
+ assert status == 0
+ assert message is not None and "boom" in message
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, None),
+ ("unauthorized", 401, False, "Invalid Mailtrap API token"),
+ ("forbidden", 403, False, "Invalid Mailtrap API token"),
+ ("server_error", 500, False, "Mailtrap returned HTTP 500"),
+ ]
+ )
+ def test_validate_credentials(
+ self, _name: str, status: int, expected_valid: bool, expected_message: str | None
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = status < 400
+ with patch.object(mailtrap, "make_tracked_session", return_value=self._session(response)):
+ assert validate_credentials("token") == (expected_valid, expected_message)
+
+
+class TestMailtrapSourceResponse:
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = mailtrap_source(
+ api_token="token",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ config = MAILTRAP_ENDPOINTS[endpoint]
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ if config.incremental_param:
+ # The watermark must only commit once a sync completes: email_logs is documented
+ # newest-first and suppressions ordering is undocumented.
+ assert response.sort_mode == "desc"
+ assert response.partition_keys == [config.partition_key]
+ assert response.partition_mode == "datetime"
+ else:
+ assert response.sort_mode == "asc"
+ assert response.partition_mode is None
+
+ def test_email_logs_primary_key_is_message_id(self) -> None:
+ assert MAILTRAP_ENDPOINTS["email_logs"].primary_keys == ["message_id"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/tests/test_mailtrap_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/tests/test_mailtrap_source.py
new file mode 100644
index 000000000000..96c4c9ce7357
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/tests/test_mailtrap_source.py
@@ -0,0 +1,149 @@
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import MailtrapSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.mailtrap.mailtrap import MailtrapResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.mailtrap.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.mailtrap.source import MailtrapSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+INCREMENTAL_ENDPOINTS = {"email_logs", "suppressions"}
+
+
+class TestMailtrapSource:
+ def setup_method(self) -> None:
+ self.source = MailtrapSource()
+ self.team_id = 123
+ self.config = MailtrapSourceConfig(api_token="token")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.MAILTRAP
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Mailtrap"
+ assert config.label == "Mailtrap"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/mailtrap"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_token"]
+
+ def test_api_token_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_token")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_no_connection_host_fields(self) -> None:
+ # The only field is the secret API token; the base URL is hardcoded, so there is no
+ # non-secret field an editor could retarget to reuse a preserved token against another host.
+ assert self.source.connection_host_fields == []
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_covers_all_endpoints(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_get_schemas_incremental_support(self, endpoint: str) -> None:
+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)
+ if endpoint in INCREMENTAL_ENDPOINTS:
+ assert schema.supports_incremental is True
+ assert schema.supports_append is True
+ assert [f["field"] for f in schema.incremental_fields] == (
+ ["sent_at"] if endpoint == "email_logs" else ["created_at"]
+ )
+ else:
+ assert schema.supports_incremental is False
+ assert schema.supports_append is False
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["email_logs"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "email_logs"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+
+ @parameterized.expand(
+ [
+ ("401 Client Error: Unauthorized for url: https://mailtrap.io/api/email_logs",),
+ ("403 Client Error: Forbidden for url: https://mailtrap.io/api/suppressions",),
+ ]
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("500 Server Error: Internal Server Error for url: https://mailtrap.io/api/email_logs",),
+ ("429 Client Error: Too Many Requests for url: https://mailtrap.io/api/suppressions",),
+ ]
+ )
+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mailtrap.source.validate_credentials")
+ def test_validate_credentials_delegates_to_shared_helper(self, mock_validate: mock.MagicMock) -> None:
+ mock_validate.return_value = (False, "Invalid Mailtrap API token")
+ result = self.source.validate_credentials(self.config, self.team_id)
+ assert result == (False, "Invalid Mailtrap API token")
+ mock_validate.assert_called_once_with("token")
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is MailtrapResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mailtrap.source.mailtrap_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "email_logs"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_token"] == "token"
+ assert kwargs["endpoint"] == "email_logs"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mailtrap.source.mailtrap_source")
+ def test_source_for_pipeline_drops_watermark_on_full_refresh(self, mock_source: mock.MagicMock) -> None:
+ # A stale watermark left over from a previous incremental sync must not leak into a full
+ # refresh, or the refresh silently skips older history.
+ inputs = mock.MagicMock()
+ inputs.schema_name = "email_logs"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "not_a_table"
+ with pytest.raises(ValueError, match="Unknown Mailtrap schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)