Skip to content

feat(emails): send cc, bcc and attachments with a code send - #367

Open
Silthus wants to merge 11 commits into
mainfrom
feat/emails-attachments
Open

Silthus wants to merge 11 commits into
mainfrom
feat/emails-attachments

Conversation

@Silthus

@Silthus Silthus commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

An email sent from code often needs a copy to someone else, or a file such as an invoice or a receipt. The .NET SDK's code send takes neither, so a .NET app has to fall back to hand-written HTTP for those emails. This PR adds Cc, Bcc and Attachments to SendCodeEmailOptions. It matches posthog-node (PostHog/posthog-js#5514) and posthog-python (PostHog/posthog-python#1172), against the server contract in PostHog/posthog#127988.

Stacked on #365, which adds PostHogClient.Emails.

await posthog.Emails.SendAsync(new SendCodeEmailOptions
{
    To = "[email protected]",
    TemplateKey = "invoice",
    Subject = "Your invoice",
    Html = "<p>Thanks!</p><img src=\"cid:logo\">",
    Cc = ["[email protected]"],
    Attachments =
    [
        new EmailAttachment { Filename = "invoice.pdf", Content = await File.ReadAllBytesAsync(path), ContentType = "application/pdf" },
        new EmailAttachment { Filename = "logo.png", Content = logoBytes, ContentId = "logo" },
    ],
});

Impact

No metric: the SDK emits no events, and the server's send logs (#127988) are where code sends with copies or attachments show up. It pays into Grow Workflows.

Merge risk

Note

Low risk, one-way door (public API). The change is additive: three new optional properties on SendCodeEmailOptions and a new EmailAttachment class. Once released, they are API that customers compile against. A send that leaves all three out sends the same body as before.

Release order. These fields need the server side deployed: PostHog/posthog#127988 (Django), plus #127985, #127995 and #127986 (cdp-api and the email workers). They sit on top of #127122 and #127123, which #365 already waits for. Until they deploy, a send with any of the three fields is refused with a validation_error that names the field. Don't merge or release this until sends with these fields are live and usable for customers, which is later than the server deploy.

What it does

  • Options. SendCodeEmailOptions gets:
    • Cc and Bcc: lists of bare addresses, at most 10 each;
    • Attachments: a list of EmailAttachment, at most 10 and 512 KB in total.
  • EmailAttachment. It holds:
    • Filename: required, the name the recipient sees;
    • Content: required, the bytes as ReadOnlyMemory<byte>, sent as standard Base64;
    • ContentType: optional MIME type;
    • ContentId: optional, shows the file inline as cid:<id>.
  • Body. The fields go out as cc, bcc and attachments: [{filename, content, content_type?, content_id?}]. An empty list is left out of the request, as in posthog-node.
  • Client checks. These throw ArgumentException before any request, like the code form's other option checks:
    • a blank address in Cc or Bcc;
    • a null attachment;
    • an attachment with a blank Filename.
  • Server checks. The server owns the limits: counts, total size, blocked file types, address format and MIME format. A refusal comes back as EmailException with Name = validation_error and Field set to the field it refused.

Divergence from sdk-specs. openspec/specs/emails/spec.md in PostHog/sdk-specs covers only the template form, with no code form, copies or attachments. This follows posthog-node and posthog-python. One .NET-specific choice: Content takes bytes only, while the other SDKs also take a Base64 string (see the decisions below).

💚 How did you test it?

Everything below ran at head 493972e.

  • Live run against the real server. The stack was feat(messaging): send cc, bcc and attachments on a code send posthog#127988 (Django, e09eec3e49f) and #127986 (cdp-api and the email workers, a239b6bbc48, with #127995 and #127985 below it), plus a mail catcher and a recording proxy in front of Django. A console app drove this branch's PostHogClient. Every case matched:

    Case Result
    Code send with one Cc, two Bcc, a PDF (ContentType application/pdf) and a PNG (ContentId logo) 202. One message reaches to, the cc address and both bcc addresses. The Cc: header lists the cc address, and no header shows a bcc address. The PDF arrives as an attachment and the PNG inline as Content-ID: <logo>, and each file's sha256 matches the bytes sent.
    GetAsync on that ID sent
    Same send, same key Replayed = true, the same ID, and no second mail
    Cc, Bcc and Attachments all empty 202, and the request body has none of the three keys
    An attachment named tool.exe 400 → validation_error, Field attachments__0__filename, with Why and Fix
    Three 200 KB files 400 → validation_error, Field attachments: at most 512 KB in total
    Cc = ["Jane <[email protected]>"] 400 → validation_error, Field cc__0: a bare address only
    11 Bcc addresses 400 → validation_error, Field bcc: at most 10

    None of the refused sends delivered mail. The readback found the Cyclotron job, the email_status row and the idempotency key in Valkey. A snapshot of the attachments table while the job was queued showed both files, with sizes and sha256 that match the bytes sent. After the send the table holds no rows for the team.

  • Cross-version: a server without this change. Each setup sent the attachments case and a Cc-only send:

    • #127988's Django with an older cdp-api (#127122, eb265457934): both are refused with 400 → validation_error, Field cc, "PostHog doesn't take this field yet, so it didn't send the email."
    • #127123's Django, without #127988 (213fad657c0): both are refused with 400 → validation_error, Field attachments or cc, "PostHog doesn't take this field, so it doesn't send the email without it."

    In both setups no job is queued and no mail goes out, as the XML docs and the changeset say. A server older than #127123 refuses every code send, as feat(emails): send transactional email with client.Emails #365's cross-version run showed.

  • CI on 493972e: build, format, tests on netcoreapp3.1 and net8.0, packaging, and the SDK compliance tests all pass. The repo's build workflow only runs on its own for PRs into main, so I started it on this branch by hand. CodeQL can't be started by hand, so it runs once feat(emails): send transactional email with client.Emails #365 merges and this PR targets main.

  • Lane gate on 493972e, with the CI steps run locally: dotnet restore --locked-mode, bin/fmt --check, dotnet build -c Release, dotnet test -c Release (1649 passed on net8.0, 1639 on netcoreapp3.1). Exit 0.

  • Unit tests. tests/UnitTests/Emails/EmailsTests.cs drives a real PostHogClient through Emails.SendAsync, with a recording HttpMessageHandler as the only fake.

    • SendsCopiesAndAttachments checks the exact request body, including the Base64 of a sliced ReadOnlyMemory<byte> and of a whole array.
    • LeavesOutEmptyCopyAndAttachmentLists checks that empty lists add no keys.
    • InvalidCodeSends covers a blank Cc and Bcc address, a null attachment, and a blank Filename. Each one throws before any request.
  • Server-side observation, not an SDK defect. As on feat(emails): send transactional email with client.Emails #365, the status route answered 404 for the first poll 76 ms after the 202, and sent 2 s later.

📝 Checklist

  • All commits are signed (see Commit signing)
  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed. (XML docs on the new members. Usage docs live on posthog.com.)
  • No breaking change or entry added to the changelog.

If releasing new changes

  • Ran pnpm changeset to 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 as one slice of the transactional-email-from-code work, to bring every server SDK to parity with posthog-node and posthog-python.

Reviewed by a cross-model panel: GPT-6.1 Sol on correctness, risk, design and anti-overengineering, Claude Opus 5.5 on fresh eyes, then a narrow second round and a final read on GPT-6.1 Sol. Fixed: System.Text.Json now writes the attachment Base64, replacing a hand-written helper with per-target branches; the older-server note moved to the class remarks, so it shows for Cc and Bcc; one comment removed. Rejected: a shadow diff, because a send without the new fields produces the same body as before, which the existing exact-body tests pin. The claim that an older server refuses the fields was checked in the server code and then shown by the cross-version run.

Question Answer Who Where
Which fields, and with what shape? cc, bcc and attachments, as in posthog-node, posthog-python and the server contract 👤 Human PostHog/posthog#127988
Merge or release now? No: hold until the server side deploys 👤 Human merge risk above
Attachment content type ReadOnlyMemory<byte> only. The other SDKs also take a Base64 string, but a .NET caller with one calls Convert.FromBase64String, and a typed byte buffer can't be a malformed string. Arrays, slices and pooled buffers all fit without a copy 🤖 Agent this PR
Client-side checks Only what the SDK can't send at all: a blank address, a null file, a blank filename, as ArgumentException like the other option checks. Limits, file types and formats stay on the server, so they change in one place 🤖 Agent this PR
Empty lists Left out of the request, as in posthog-node 🤖 Agent this PR

Involvement: no grilling rounds, no prototypes, 2 review rounds (one 5-lens panel, one 3-lens fixes round) and 1 clean final read, and live-run plus cross-version proof captured.

🤖 Generated with Claude Code

Silthus and others added 9 commits November 2, 2026 16:03
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 <[email protected]>
- 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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
@Silthus Silthus self-assigned this Nov 4, 2026
@github-actions

github-actions Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

posthog-dotnet Compliance Report

Date: 2026-11-04T08:19:28.504137+00:00
Duration: 124767ms

✅ All Tests Passed!

47/47 tests passed


Capture Tests

✅ 30/30 tests passed

View Details
Test Status Duration
Format Validation.Event Has Required Fields ✅ 218ms
Format Validation.Event Has Uuid ✅ 122ms
Format Validation.Event Has Lib Properties ✅ 108ms
Format Validation.Distinct Id Is String ✅ 113ms
Format Validation.Token Is Present ✅ 108ms
Format Validation.Custom Properties Preserved ✅ 114ms
Format Validation.Event Has Timestamp ✅ 109ms
Format Validation.Non Utc Event Timestamp Is Converted To Utc ✅ 119ms
Retry Behavior.Retries On 503 ✅ 8121ms
Retry Behavior.Does Not Retry On 400 ✅ 2116ms
Retry Behavior.Does Not Retry On 401 ✅ 2113ms
Retry Behavior.Respects Retry After Header ✅ 8121ms
Retry Behavior.Implements Backoff ✅ 22123ms
Retry Behavior.Retries On 500 ✅ 6120ms
Retry Behavior.Retries On 502 ✅ 6115ms
Retry Behavior.Retries On 504 ✅ 6118ms
Retry Behavior.Max Retries Respected ✅ 22135ms
Deduplication.Generates Unique Uuids ✅ 115ms
Deduplication.Preserves Uuid On Retry ✅ 6116ms
Deduplication.Preserves Uuid And Timestamp On Retry ✅ 13129ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 6120ms
Deduplication.No Duplicate Events In Batch ✅ 116ms
Deduplication.Different Events Have Different Uuids ✅ 110ms
Compression.Sends Gzip When Enabled ✅ 108ms
Batch Format.Uses Proper Batch Structure ✅ 108ms
Batch Format.Flush With No Events Sends Nothing ✅ 105ms
Batch Format.Multiple Events Batched Together ✅ 113ms
Error Handling.Does Not Retry On 403 ✅ 2110ms
Error Handling.Does Not Retry On 413 ✅ 2112ms
Error Handling.Retries On 408 ✅ 6115ms

Feature_Flags Tests

✅ 17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id ✅ 139ms
Request Payload.Flags Request Uses V2 Query Param ✅ 108ms
Request Payload.Flags Request Hits Flags Path Not Decide ✅ 107ms
Request Payload.Flags Request Omits Authorization Header ✅ 108ms
Request Payload.Token In Flags Body Matches Init ✅ 107ms
Request Payload.Groups Round Trip ✅ 111ms
Request Payload.Groups Default To Empty Object ✅ 107ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False ✅ 108ms
Request Payload.Disable Geoip Omitted Defaults To False ✅ 108ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key ✅ 107ms
Request Lifecycle.No Flags Request On Init Alone ✅ 3ms
Request Lifecycle.No Flags Request On Normal Capture ✅ 106ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests ✅ 211ms
Request Lifecycle.Mock Response Value Is Returned To Caller ✅ 110ms
Retry Behavior.Retries Flags On 502 ✅ 1113ms
Retry Behavior.Retries Flags On 504 ✅ 1109ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event ✅ 211ms

Silthus and others added 2 commits November 4, 2026 08:04
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 <[email protected]>
@Silthus

Silthus commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@PostHog review

@posthog

posthog Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

@Silthus PostHog Review is reviewing this pull request.

@posthog posthog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PostHog Review · Standard · reviewed 493972e: no findings.

@Silthus
Silthus marked this pull request as ready for review November 4, 2026 08:38
@Silthus
Silthus requested a review from a team as a code owner November 4, 2026 08:38
stamphog[bot]

This comment was marked as outdated.

@Silthus
Silthus changed the base branch from feat/emails-send to main November 5, 2026 12:09
@stamphog
stamphog Bot dismissed their stale review November 5, 2026 12:09

The PR was retargeted to a different base branch, so the approved diff is no longer what was reviewed. Stamphog re-reviews automatically.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants