Repository navigation
feat(emails): send cc, bcc and attachments with a code send - #367
Conversation
Add IPostHogClient.Emails, a port of posthog-node's and posthog-python's emails API. SendAsync sends a template made in PostHog by its ID, or content the app rendered, named by a template key, as the flat body of POST /api/projects/@current/messaging/send/email/. GetAsync reads an email's status. Every attempt of a send carries the same idempotency key. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Serialize read-only dictionaries without recursing into the same converter, so ReadOnlyDictionary template data no longer overflows the stack. - Give IPostHogClient.Emails a default implementation where the target allows it, as EvaluateFlagsAsync does, so custom implementers keep compiling. - Drain email requests while the event batch flushes, instead of before it. - ConfigureAwait(false) on every await in EmailSender, so a synchronous Dispose can't deadlock on a captured context. - Name an invalid AppHost in the missing_app_host message. - Drop the unused jitter seam, the unreachable body-read fallback and the inline comments; use UUID message IDs in the send fixtures. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Copy the entries into a Dictionary and let System.Text.Json's own dictionary converter write them, so non-string keys keep their JSON property-name format. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Write one property per entry the source enumerates, with the key type's own JSON property-name converter, instead of copying into a Dictionary whose default comparer could merge keys the source keeps apart. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
System.Text.Json's string converter already applies DictionaryKeyPolicy, so a custom string key converter keeps working with a naming policy. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Adding Emails to IPostHogClient broke custom implementers on netstandard2.0, which has no default interface members. Emails now lives on PostHogClient, and AddPostHog registers the client's IPostHogEmails for injection. Dispose() runs DisposeAsync off the caller's synchronization context, so a synchronous dispose on a single-threaded context can't deadlock while an email request or the event flush is still running. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…omments Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
posthog-dotnet Compliance ReportDate: 2026-11-13T06:26:54.177693+00:00 ✅ All Tests Passed!47/47 tests passed Capture Tests✅ 30/30 tests passed View Details
Feature_Flags Tests✅ 17/17 tests passed View Details
|
Also move the older-server note to the SendCodeEmailOptions remarks, so it shows for Cc and Bcc too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
@PostHog review |
|
@Silthus PostHog Review is reviewing this pull request. |
The PR was retargeted to a different base branch, so the approved diff is no longer what was reviewed. Stamphog re-reviews automatically.
# Conflicts: # src/PostHog/Config/PostHogConfigurationBuilder.cs # src/PostHog/Emails/EmailSender.cs # src/PostHog/Emails/IPostHogEmails.cs # src/PostHog/Emails/SendEmailOptions.cs # src/PostHog/Examples.cs # src/PostHog/PostHogClient.cs # src/PostHog/PublicAPI.Unshipped.txt # tests/UnitTests/Emails/EmailsTests.cs
SDK performance: posthog-dotnetBenchmarks completed. No changes flagged for review. Flags require at least a 5% change in the median and all six pairs agreeing on direction. This is a noise filter, not proof of a performance change or a CI gate. View all results
Values are medians of paired measurements. Not flagged does not mean unchanged. Unavailable means a measurement could not be provided, not zero. Estimated allocation measurements retain their instrumentation uncertainty. RSS measures the whole process, not just SDK allocations; observed peaks are sampled checkpoints. Paired ranges in the diagnostics describe variability, not confidence intervals. Compared 108 metric rows; 108 rows shown in all results. Omitted or shortened data remain in |
|
Note 🤖 Claude Opus 5.5 responding on behalf of Michael On hold, and back to draft. The attachments API moves to upload first, then send: the SDK hashes each file, uploads it, and sends a reference instead of Base64 content. This PR gets reworked to that shape, cc and bcc included, and nothing merges until the server side is live. |
A send with files asks the upload route which files PostHog lacks, PUTs each one to the storage URL with exactly the returned headers and no bearer token, and sends references by SHA-256. It refuses more than 10 files or a message over the 40 MB estimate before any request. Refs PostHog/michaelr-context#85 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An upload method of only whitespace made HttpMethod throw ArgumentException on .NET 8, which escaped SendAsync instead of the api_error on the file that every other unusable upload answer gets. Refs PostHog/michaelr-context#85 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
New commits were pushed — dismissing the stamphog approval from an earlier head. Re-add the trigger label to request a fresh review.
|
@PostHog review |
|
@Silthus PostHog Review is reviewing this pull request. |
There was a problem hiding this comment.
PostHog Review · Standard · reviewed bd447e9: 1 Should fix.
This is review round 3 on this pull request. When findings keep coming back in the same code, the approach is usually the problem. Before the next fix, check whether a different design would remove the whole class of findings.
An HttpClient that follows a 307 or 308 re-sends the PUT body to the new URL and reports success, so a redirect could carry a file away from the URL PostHog signed. Uploads now go through their own HttpClient, PostHogClient.Uploads, whose handler never follows redirects, in both the default factory and the AddPostHog registration. A 3xx answer fails the attachment with attachment_upload_failed, naming the file but not the URL. The upload client carries none of the app's handlers or default headers, so the client_authorization_header refusal is gone; uploads keep the app client's Timeout. The new test runs a real PostHogClient over loopback sockets, through both wirings, against a storage that redirects the PUT to a second server. Refs PostHog/michaelr-context#85 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
New commits were pushed — dismissing the stamphog approval from an earlier head. Re-add the trigger label to request a fresh review.
|
@PostHog review |
|
@Silthus PostHog Review is reviewing this pull request. |
There was a problem hiding this comment.
PostHog Review · Standard · reviewed 0fd6634: 1 Should fix.
This is review round 4 on this pull request. When findings keep coming back in the same code, the approach is usually the problem. Before the next fix, check whether a different design would remove the whole class of findings.
Uploads now always go through an HttpClient the SDK makes, with a handler that never follows a redirect, so an app's IHttpClientFactory can no longer hand out a redirect-following client for them. The client is disposed with PostHogClient. Tests cover an app-supplied factory over the network, a stalled upload against the app's HttpClient.Timeout, caller cancellation of an upload, and an upload outlasting EmailRequestTimeout. Context: PostHog/michaelr-context#85 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
@PostHog review |
|
@Silthus PostHog Review is reviewing this pull request. |
There was a problem hiding this comment.
PostHog Review · Standard · reviewed 9898942: 1 Should fix.
This is review round 5 on this pull request. When findings keep coming back in the same code, the approach is usually the problem. Before the next fix, check whether a different design would remove the whole class of findings.
…ains uploads EmailSender was IDisposable, so a DI container that handed it out through AddPostHog disposed it before PostHogClient drained the sends, cutting an upload in flight. PostHogClient now owns the upload client and disposes it after the drain; the sender only uses it. A test shuts the host down while an upload is held and expects the email delivered. Context: PostHog/michaelr-context#85 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
@PostHog review |
|
@Silthus PostHog Review is reviewing this pull request. |
…ng it Context: PostHog/michaelr-context#85 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
@PostHog review |
|
@Silthus PostHog Review is reviewing this pull request. |
Keeps main's tracking and sensitivity on code sends beside this branch's cc, bcc and attachments: the send body, SendCodeEmailOptions, the public API list and the tests carry both, and the fake send route accepts sensitive and tracking. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
New commits were pushed — dismissing the stamphog approval from an earlier head. Re-add the trigger label to request a fresh review.
GitHub's ubuntu-26.04 runner image 20261103 ships the .NET 11 SDK, and with no global.json the build picks it. Its analyzers raise CA1860 on this line, which fails `dotnet pack` for PostHog.AspNetCore on those runners. Same result for null or empty chains; no behavior change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Approved.
The disclosed changes enter risky territory, but the author's STRONG familiarity supplies the policy's assurance path and the diff includes extensive tests. No concrete unresolved reviewer concern or other policy showstopper is evidenced in the supplied context and current code.
- Author wrote 94% of the modified lines and has 2 merged PRs in these paths (familiarity STRONG).
Gate mechanics and policy version
| Gate | Result | |
|---|---|---|
| prerequisites | ✓ | all clear |
| deny-list | ✓ | no deny categories matched |
| size | ✓ | 595L, 7F substantive, 1688L/13F incl. docs/generated/snapshots — within ceiling |
| tier | ✓ | T1-agent / T1d-complex (1688L, 13F, cross-cutting, feat) |
| stamphog 2.8.0 | .stamphog/policy.yml @ e458830 · reviewed head e458830 |
Merge gate: node-store (#77) and django-facade (#78) live in both regions, the allowlist at * in both regions, and a real send through this SDK version with a real project key, delivered and confirmed by Michael. Then the repo's normal release.
💡 Motivation and Context
An email sent from code often needs a copy to someone else, or a file such as an invoice. The .NET SDK's code send takes neither, so a .NET app falls back to hand-written HTTP for those emails, and inline Base64 capped files at 512 KB in total.
With this PR,
SendCodeEmailOptionstakesCc,BccandAttachments: up to 10 files and 40 MB per email after Base64 encoding, about 29 MB of files. The SDK names each file by its SHA-256, uploads only the files PostHog doesn't have yet straight to PostHog's file storage, and then sends the email naming the files by hash. A file sent before isn't uploaded again.Ticket: PostHog/michaelr-context#85. Server contract: PostHog/posthog#131664 (upload route), PostHog/posthog#131763 (references on sends), PostHog/posthog#131833 and PostHog/posthog#131944 (cdp-api).
Impact
No SDK metric: the SDK emits no events. The server captures attachment counts and bytes on every send outcome and on the upload route, and that is where code sends with files show up.
Caution
🔴 Merge risk: high · one-way door once the release publishes to NuGet:
Cc,Bcc,AttachmentsandEmailAttachmentbecome public API that apps compile against. Merging starts the release workflow, which waits for a maintainer's approval before it publishes.CcorBcc(new; no app can set them before the release) now carryccandbcc, without files too. A PostHog that doesn't take them refuses withvalidation_errornaming the field and sends nothing. The unit tests cover both against the fake; against a real server that takes them the row is uncovered until the real send (accepted cross-version gap), and a missed bug there fails or misaddresses that copy. Sends that set neither, or set empty lists, send the same body as before (shadow diff).LocalEvaluationApiResultreadsDependencyChain's count instead ofAny(), the CA1860 fix. Null and empty chains compare as before, so no flag outcome changes; the local-evaluation unit tests pass unchanged.field_not_acceptedbefore any upload; fix forward.Rollout
*in both regions; then the normal release.What it does
SendCodeEmailOptionsgetsCcandBcc(bare addresses, at most 10 each) andAttachments, a list ofEmailAttachment:Filename,ContentasReadOnlyMemory<byte>, optionalContentTypeandContentId(inline ascid:<id>). Unchanged from the earlier version of this PR.EmailExceptiontoo_many_attachments. A message over PostHog's estimate throwsmessage_too_large: 64 KiB, plus the subject as folded encoded words (75 bytes per 42 UTF-8 bytes), plus every file and both bodies as Base64 in 76-character lines, at most 40,000,000 bytes, the server's own formula. WithoutText, PostHog sends text it derives from the HTML, so the HTML counts twice: the derived text only drops tags and shortens entities and links, so it is never longer. Both carryWhy,Fix,Field = attachmentsandName = validation_error, as the server's refusal would. A null file, a blankFilenameor an empty file throwsArgumentException.POST /api/projects/@current/messaging/attachments/uploads/with{files: [{sha256, size}]}, once per distinct hash, with the secret key. A file PostHog answerspresentis skipped. A 404 from the route throws PostHog's own answer,not_foundonattachmentswith its reason, and sends nothing: a PostHog without the route and a project that can't send email from code both answer 404, and the client can't tell them apart.uploadfile is PUT to the returned URL with the returned method and exactly the returned headers. NoAuthorizationand noX-PostHog-Migrated-From: the URL is presigned. Network errors and the storage's 429 and 5xx answers are retried with the send's retry budget. Any other refusal throwsattachment_upload_failedwith the storage's HTTP status, its error code and message inWhy(for exampleHTTP 400 BadDigest: ...), andField = attachments__<i>. No email is sent. ItsNamecomes from the storage's answer,service_unavailablefor 429 and 5xx andapplication_errorotherwise, so an expired URL's 401 or 403 never reads as a missing PostHog key or scope.insecure_app_hostonattachments__N, naming the file and holding no URL, unlessAllowInsecureAppHost, the existing opt-in for local development, is set. No new option. Uploads go through anHttpClientthe SDK makes for them, whateverIHttpClientFactorythe app passes, whose handler never follows a redirect (AllowAutoRedirect = false): a client that follows a 307 or 308 re-sends the PUT body to the new URL and reports success. A 3xx answer fails that file withattachment_upload_failed, naming the file but never a URL, and sends nothing. That client carries none of the app's handlers or default headers, so neither credentials nor files leave for another host; it uses the system proxy, andPostHogClientowns it and disposes it only after the sends drain, so a host shutting down throughAddPostHogstill delivers a send whose upload is in flight.attachments: [{sha256, filename, content_type?, content_id?}]in the caller's order, duplicates included.upload_quota_exceededis a daily cap, so it isn't retried; its other 429s and 503s are. PostHog's own 500s still aren't.EmailRequestTimeout, which sizes a JSON request; a large file runs until the app's PostHogHttpClient.Timeout(thennetwork_error, "timed out") or the caller cancels (OperationCanceledException).sdk-specs.
openspec/specs/emails/spec.mdin PostHog/sdk-specs covers only the template form, with no code form, copies or attachments. This follows the cross-SDK spec for this work in PostHog/michaelr-context#85.💚 How did you test it?
Lane gate at
e458830, with main merged in:dotnet restore --locked-mode,bin/fmt --check,dotnet build -c Release(0 warnings),dotnet test -c Release -f net8.0: 1795 passed and 2 skipped in UnitTests, 75 in UnitTests.AspNetCore, 29 in PostHog.AI.Tests. netcoreapp3.1 ran in CI only: this devbox lacks the OpenSSL 1.1 its test host needs.CI at
e458830: build, format, packaging, tests on netcoreapp3.1 and net8.0, and semgrep pass.e458830(runner image fix). GitHub's runner image 20261103 ships the .NET 11 SDK, and with noglobal.jsonthe build picks it. Its analyzers raised CA1860 on an unchanged line on main (LocalEvaluationApiResult'sDependencyChain?.Any()), which failedPackage (PostHog.AspNetCore)on those runners only. It now readsis not { Count: > 0 }: the same result for null or empty chains. The whole solution builds with 0 errors under SDK 11.0.100, and the unit tests pass there too.Main merged in at
fa2aaad(a merge commit, no rebase). Main'sTrackingandSensitiveon code sends sit besideCc,BccandAttachmentsinSendCodeEmailOptions, the send body and the public API list, and the fake send route acceptssensitiveandtracking. The live run and shadow diff below ran again ate458830, the shadow diff against the new merge base9e9d963; the cross-version run is from8786a60, before the merge.Release.
.changeset/emails-cc-bcc-attachments.mdselectsPostHogfor a minor release. Merging tomainstarts the release workflow: it waits for a maintainer's approval in theReleaseenvironment, then bumps the version, writes the CHANGELOG, and publishes to NuGet.Red, then green. The attachment tests in
TheSendAsyncMethodWithAttachmentsfail on the inline-Base64 code (tests commit6d18cb5) and pass at HEAD. Each review fix's tests failed on the commit before it: 13 cases on3ea4218, 1 on05043cb, 3 onb440ea6, 5 subject cases with the subject left out of the estimate, the empty file on6d22616, for698ba372 HTML-only cases with the derived text left out of the estimate and theAllowInsecureAppHostupload case with the opt-in ignored, a whitespace-only upload method on698ba37, and for0fd6634the redirect test with the upload client following redirects (both wirings red) and with a 3xx answer quoting the storage's body (both red), and for9898942the app-suppliedIHttpClientFactorywiring on0fd6634(red; the other two wirings green), a stalled upload with the app's timeout removed or replaced byEmailRequestTimeout, caller cancellation with the cancel filter removed, and an upload outlastingEmailRequestTimeoutwith that timeout applied (each red), and for352e858a host shutting down throughAddPostHogwhile an upload is held, red on9898942.Test seam: a real
PostHogClientthroughEmails.SendAsyncagainstFakePostHogEmails, a stateful fake of the upload route, the file storage and the send route. The upload route answerspresentfor stored files and presigns the rest; the storage takes a PUT only with the signed length and checksum and no other credential, refuses a body whose SHA-256 doesn't match, and stores the bytes; the send route refuses a file it doesn't store. Each route refuses keys outside the real serializers. Tests assert the delivered email (copies, file names, types, content IDs and stored bytes) and the storage's writes, not request strings. Faults the real peers can't be made to give (storage 5xx, a proxy's refusal, garbled answers, the daily cap) are injected and the tests still assert the outcome. Mutation-checked: a bearer token on the PUT, the wrong slice uploaded, a duplicate file asked for twice. The redirect rule runs over real sockets instead, because a fake transport skips the HTTP stack's redirect handling: a realPostHogClient, wired bynew PostHogClient, bynew PostHogClientwith an app's plainservices.AddHttpClient()factory, and byservices.AddPostHog, againstFakePostHogEmailsserved on loopback, whose storage answers the PUT with a 307 to a second loopback server that must receive nothing. The estimate's edges are hand-computed from the server's formula: 29,182,821 bytes fit beside a subject of up to 42 UTF-8 bytes and 29,182,875 beside an empty one; one more file, subject, HTML or text byte is refused.Shadow diff. The merge base and HEAD ran the same 12 sends without files (template and code sends, refusals 400, 401, 422, 429 and 500, a 503 retry, a validation error, status reads 200 and 404) against one recording server. Requests and outcomes are identical.
Live run against real object storage, at
e458830. This branch'sPostHogClientin a console app; a stand-in for the upload and send routes that presigns PUT URLs the way the cdp-api store does (SigV4,content-lengthandx-amz-checksum-sha256signed, the checksum not hoisted into the query); SeaweedFS with credentials, so it checks every signature. Its URLs are plain http, uploaded throughAllowInsecureAppHost. The SDK made every request:CcandBccupload; both PUT; send accepted. The stored objects' SHA-256 match the bytes.present; no PUT; send accepted.400 BadDigest;attachment_upload_failed,Nameapplication_error,Fieldattachments__0; the send route is never called.403 AccessDenied: Request has expired;attachment_upload_failed,Nameapplication_error; no send.too_many_attachments; no request at all.Endpoint not found.404not_found,Fieldattachments, PostHog's reason as the message; no PUT, no send.message_too_large; no request at all.message_too_large; no request at all.Textbeside a 29,170,000-byte filemessage_too_large; no request at all.TextArgumentException; no request at all.attachment_upload_failed,Fieldattachments__0, no URL in the error; the other URL received nothing; no send.Cross-version, against today's PostHog Cloud (US and EU, a dummy key, at
8786a60): a send with a file asks the upload route, which answers404 Endpoint not found.; the SDK reportsnot_foundonattachmentswith that reason and makes no upload and no send. Acc-only send reaches today's send route and stops at authentication (401 authentication_failed).Gaps. No run against a PostHog that has the new routes: the server side is unmerged and runs nowhere yet. The opening stack's real send from PostHog's own team proves that path before this SDK releases.
📝 Checklist
If releasing new changes
pnpm changesetto generate a changeset file (.changeset/emails-cc-bcc-attachments.md, minor)🤖 Agent context
Autonomy: Human-driven (agent-assisted)
Built by Claude Opus 5.5 (
claude-opus-5-5, high effort) in Claude Code, directed by Michael. It reworks this PR's inline Base64 attachments into hash, upload, then send, following the cross-SDK spec for moving email attachments to object storage.EmailExceptionwith the server's codes (too_many_attachments,message_too_large), so onecatchhandles the client's and the server's refusal;ArgumentExceptionstays for a null file, a blank name or an empty filecontent_too_largeHttpClient's own timeout, notEmailRequestTimeout, which a large file can outlastReadOnlyMemory<byte>only, as before; arrays, slices and pooled buffers fit without a copyHttpClientthe SDK makes, owned byPostHogClientand disposed after the sends drain, never one from the app'sIHttpClientFactory, that never follows a redirect and carries none of the app's handlers or default headers; the system proxy applies, the app's PostHogTimeoutbounds each PUT. Replaces the shared client and itsclient_authorization_headerrefusalnot_foundonattachments, neverfield_not_accepted: the client can't tell a missing route from email from code being offText, the HTML counts twice, an upper bound of the text PostHog derives, so a send that passes locally isn't refused after its uploadsArgumentExceptionbefore any request: the upload route takes only files of at least one byteNamerate_limit_exceeded, as the emails spec names every 429 butquota_limited;Codetells the cap apart, and it isn't retriedInvolvement: no grilling rounds, no prototypes; one design pass (GPT-6.1 Sol); review panel round 1 (six lenses, GPT-6.1 Sol and Claude Opus 5.5), round 2 and two final reads (GPT-6.1 Sol); full panels on each new head, rounds 3 to 7 and 9, round 11 over the whole diff at
352e858, and round 12 on the final head8786a60, which only renames a test variable in place of a comment (nine lenses including the Team perspectives, GPT-6.1 Sol and Claude Opus 5.5); rounds 8 and 10 a single reviewer (GPT-6.1 Sol) where a panel failed to start; PostHog Review; round 13 one458830(the main merge and the CA1860 fix), a single reviewer (GPT-6.1 Sol), no findings; live-run and shadow-diff proofs ate458830, cross-version at8786a60.🤖 Generated with Claude Code