Repository navigation
feat: send report and alert emails through smtp connectors - #10262
nishantmonu51 wants to merge 14 commits into
Conversation
- New `runtime/drivers/smtp` driver with host, port, username, password, tls_mode, from and from_name; it returns an email.Sender through the new drivers.Handle.AsEmailSender, and its Ping logs in without sending. - The SMTP sender in runtime/pkg/email supports required STARTTLS (587), implicit TLS (465) and no TLS for local test servers, times out, and returns errors that name the failed step. - Customer connectors never get Rill's internal BCC. - Mailpit testcontainer in testruntime.Connectors with helpers to read received emails and reject steps.
- Add `email_connector` to rill.yaml; report and alert emails go through that SMTP connector, else Rill's sender. - Resolve the sender with `Runtime.EmailClient`, which takes an optional connector for notification templates. A failing connector fails the run without falling back to Rill's sender. - Record per-channel delivery results (`NotificationDelivery`) on report and alert executions. Slack still sends when email fails. - Expose `email_connector` on `GetInstance`. - Stop recording failed report runs twice in the execution history.
- Add `SendTestEmail`, which sends a test email through a saved SMTP connector or the properties of an unsaved one, and never through Rill's sender. - Report whether the server accepted it, the latency, the failed SMTP step and the server's answer. - Check the From domain's SPF record for the provider's include (following includes and redirects up to the SPF lookup limit) and its DMARC policy (falling back to the organizational domain).
- "Email connector" in the Add menu opens a dialog with presets for SendGrid, Amazon SES, Postmark, Mailgun, Google Workspace, Microsoft 365 and other SMTP servers. - The password goes to .env; the connector file references it. - "Send all report and alert emails through this connector" sets `email_connector` in rill.yaml. It defaults on only when the project has no email connector yet. - A test send before saving shows the server's answer, the latency, a fix for the failed step, and the SPF and DMARC records of the From domain. - Connector files with `driver: smtp` get a side panel: connection status, project default and report and alert counts, and a test send. - Gated by the `smtp_connectors` feature flag (default off).
- Report and alert pages show a banner when the latest run's emails weren't sent: the connector, the error, how many recipients missed it, and how it goes out again (Run now and the next run for reports, the next check for alerts). - Run history rows show one tag per channel: how many recipients got the email or that it failed (with the error in a tooltip), and the Slack post. - Runs from before per-channel results keep their single status tag. - Gated by the `smtp_connectors` feature flag.
…rs` flag - New SMTP page under Service Integrations: creating a connector in the dialog or by hand, `email_connector`, what happens when a send fails, provider settings, the test send's checks, and deploying the password. - The services index lists SMTP under Notifications; project configuration and alerts link to it. - The connector form, the side panel and the delivery failures on report and alert pages are no longer behind the `smtp_connectors` feature flag.
nishantmonu51
left a comment
There was a problem hiding this comment.
A few things to check in the delivery and setup paths.
| if opts.TLSMode == TLSModeImplicit { | ||
| conn, err = (&tls.Dialer{NetDialer: dialer, Config: tlsConfig}).DialContext(ctx, "tcp", addr) | ||
| } else { | ||
| conn, err = dialer.DialContext(ctx, "tcp", addr) |
There was a problem hiding this comment.
The Cloud network question affects saved connectors too. Saving one runs ConnectorReconciler.testConnector → PingSMTP, and scheduled sends use the same unrestricted dialer. Can all SMTP paths share the resolved-address policy used by hosted connectors in safehttp, with allow_host_access coming from trusted runtime config for both saved and unsaved tests?
There was a problem hiding this comment.
Good call, fixed in c561ee7. Unsaved test properties can't turn host access on either.
| // Unlike smtp.SendMail, it supports implicit TLS, can require STARTTLS, only authenticates when credentials are set, and times out. | ||
| // Errors are returned as *SMTPError. | ||
| func sendSMTP(opts *SMTPOptions, from string, recipients []string, message []byte) error { | ||
| c, err := dialSMTP(context.Background(), opts) |
There was a problem hiding this comment.
A report with a short timeout can keep sending after it expires if the SMTP server stalls or is slow across multiple recipients. sendSMTP starts from context.Background() and the report loop only checks cancellation after a send error. Could we pass the run or RPC context through to SMTP, close the connection on cancellation, and check the context between recipients?
There was a problem hiding this comment.
Fixed in c561ee7. I bound the context in Email.WithSender instead of adding it to Sender.Send, since that would touch every admin email call.
| release() | ||
| default: | ||
| delivery := &runtimev1.NotificationDelivery{Channel: notifier.Connector, Connector: notifier.Connector} | ||
| current.Deliveries = append(current.Deliveries, delivery) |
There was a problem hiding this comment.
If the Slack connector is unavailable, AcquireHandle returns before the code sets delivery.ErrorMessage. For an alert with error notifications off, executeAll records that execution and DeliveryTags labels the empty-error entry “Slack sent.” Could we record setup and send errors on the same delivery entry before finalizing the run?
| blob: string, | ||
| connector: string, | ||
| ): string { | ||
| const regex = /^email_connector:.*$/m; |
There was a problem hiding this comment.
If rill.yaml already has a quoted "email_connector" key, this appends a second key with the same name and the project parser rejects the file. Could we use yaml’s parseDocument and update the top-level key with doc.set so quoted keys and comments survive?
There was a problem hiding this comment.
I'd keep this in line with the olap_connector and ai_connector helpers, which use the same regex. Rill never writes quoted keys there.
| }), | ||
| queryFn: () => runtimeServiceGetFile(client, { path: "rill.yaml" }), | ||
| }); | ||
| await runtimeServicePutFile(client, { |
There was a problem hiding this comment.
If creating the connector succeeds but updating rill.yaml fails, the dialog reports a save error and the same name can’t be retried because the file already exists. Could we report that the connector was created and let the user retry just the project-default update?
There was a problem hiding this comment.
Done in 1c22fe4. Saving again now only retries the rill.yaml update.
| <span>{m.smtp_inspector_status_error()}</span> | ||
| </div> | ||
| <pre class="smtp-error">{reconcileError}</pre> | ||
| {:else} |
There was a problem hiding this comment.
While the connector’s first Ping is still running, reconcileError is empty and the inspector already says “Rill can connect to the server.” Can we show a checking state while meta.reconcileStatus is pending or running and reserve the success state for a completed check?
|
|
||
| // AsEmailSender returns an email sender if the handle can serve as such, otherwise returns false. | ||
| // An email sender delivers report and alert emails through a mail server the project configures, such as an SMTP server. | ||
| AsEmailSender() (email.Sender, bool) |
There was a problem hiding this comment.
Only SMTP implements this capability, but putting it on drivers.Handle adds a stub to every other driver. Could AsEmailSender be an optional interface on the SMTP handle, with one lookup helper shared by Runtime.EmailClient and SendTestEmail?
There was a problem hiding this comment.
Makes sense, it's an optional interface now in c561ee7.
…sEmailSender` an optional interface
…; show a checking state until its connection check finishes
…nnector # Conflicts: # runtime/runtime.go
|
|
||
| ### `from_name` | ||
|
|
||
| _[string]_ - Name that emails are sent from. Defaults to "Rill". |
There was a problem hiding this comment.
Given the general use case is for embedded customer, I would prefer to either keep this as required or default to project name.
There was a problem hiding this comment.
Went with required in 7cbc437. The project name is usually a slug, so it doesn't make a good sender name.
| } | ||
|
|
||
| // SPFCheck is the result of checking the SPF record of an email's From domain. | ||
| message SPFCheck { |
There was a problem hiding this comment.
The SPF check gives wrong advice. SPF is checked against the envelope (return-path) domain, not the From domain. SES, Postmark and SendGrid use their own return-path domain by default and pass DMARC through DKIM, so customers whose setup is correct are told to change their DNS. I suggest dropping the expected-include check and the missing-SPF warning, and pointing users to the test email's Authentication-Results header, which shows what the receiving server actually concluded. Showing the published DMARC policy, and warning when there's none, is fine to keep.
Separately, SPFCheck and DMARCCheck are only used in this response, so their fields could be inlined into SendTestEmailResponse (for example, dmarc_record and dmarc_policy).
There was a problem hiding this comment.
Agreed, dropped SPF and inlined the DMARC fields in 7cbc437. The test results point to the Authentication-Results header now.
| if port == 465 { | ||
| tlsMode = email.TLSModeImplicit | ||
| } | ||
| } |
There was a problem hiding this comment.
tls_mode: none is accepted when host access is off. On Rill Cloud, a project can point the connector at a public relay that allows unauthenticated sending, and report attachments and magic links then travel unencrypted. Please reject none here unless AllowHostAccess is set, since it is only meant for local test servers.
There was a problem hiding this comment.
Good catch, it's refused without host access now (7cbc437).
| username: "", | ||
| usernameHint: () => m.smtp_connector_hint_username_mailbox(), | ||
| passwordHint: () => m.smtp_connector_hint_password_microsoft(), | ||
| }, |
There was a problem hiding this comment.
Exchange Online advertises AUTH LOGIN XOAUTH2, not PLAIN, and dialSMTP always uses smtp.PlainAuth, so this preset can't log in even with valid credentials and SMTP AUTH enabled. I suggest removing the preset and the Microsoft 365 rows in the docs until it's verified against a real mailbox.
There was a problem hiding this comment.
Removed it from the dialog and the docs.
| release() | ||
| delivery.ErrorMessage = err.Error() | ||
| return err | ||
| } |
There was a problem hiding this comment.
If the check is cancelled after some recipients got the email (for example, during a deploy), this returns context.Canceled, and executeAll discards the current execution as if it never ran. The next check emails every recipient again, so the first ones get duplicates. Before this change the loop ignored cancellation and the run was always saved, so this also affects projects without email_connector.
Returning the error only when no channel has sent anything yet, and otherwise recording it on the delivery and saving the run, avoids the duplicates.
There was a problem hiding this comment.
Fixed in 7cbc437. An email that failed at the data step also counts as possibly sent.
|
|
||
| // EmailSenderHandle is a Handle that can send report and alert emails through a mail server the project configures, such as an SMTP server. | ||
| // Only the smtp driver implements it, so it's not part of Handle; use EmailSenderFor to look it up. | ||
| type EmailSenderHandle interface { |
There was a problem hiding this comment.
Every other driver capability is an As* method on Handle, and drivers that don't support it return nil, false. The reason given here, that only one driver implements it, applies just as much to AsMCP, which only the mcp driver supports. Adding AsEmailSender() (email.Sender, bool) to Handle next to AsNotifier would keep one way to look up a capability, and would remove EmailSenderHandle and EmailSenderFor. It adds a stub to each driver, but that's the cost every other capability already pays.
There was a problem hiding this comment.
Fair, moved it back onto Handle in 7cbc437.
| for _, recipient := range recipients { | ||
| // Stop when the check times out or is cancelled, instead of sending the remaining emails. | ||
| if err := ctx.Err(); err != nil { | ||
| release() |
There was a problem hiding this comment.
The email branch calls release() by hand in three places, and any new return path has to remember to do it too. Wrapping the branch in func() error { …; defer release() }(), as the default branch does below, makes the release automatic.
| } | ||
| defer release() | ||
| handle = h | ||
| } else { |
There was a problem hiding this comment.
This is optional, since it removes testing before saving: I suggest dropping the properties mode and only testing saved connectors. Other connectors are validated by saving them and letting the reconciler run Ping. This branch adds a second way to open a driver straight from request input, with its own allow_host_access override, so its security depends on that override never being missed. Saving first and then testing would remove it and the one-of-two check on line 43.
There was a problem hiding this comment.
I'd keep testing before saving, since it checks the credentials before anything is written to .env. The host access override has a test in TestSendTestEmail.
| if err != nil { | ||
| // The channel couldn't be set up. The run is recorded as an error, so its delivery must show the error too. | ||
| delivery.ErrorMessage = err.Error() | ||
| return err |
There was a problem hiding this comment.
When a channel fails to set up after earlier channels have sent (for example, the emails went out but the Slack connector can't be opened), this returns before the run is saved. executeAll then sets the run to ERROR and calls popCurrentExecution again, which sends the emails a second time if error notifications are on, and appends a second set of deliveries. This path already exists on main, but the deliveries make it visible. Recording the setup error like a send error (setting notificationErr and continuing) instead of returning would save the run once.
There was a problem hiding this comment.
Fixed in 7cbc437, with a test that the emails aren't sent twice.
| {formatRunDate(reportTime, timeZone)} | ||
| </div> | ||
| {#if errorMessage === ""} | ||
| {#if deliveries.length} |
There was a problem hiding this comment.
When a run has deliveries, the row hides the run's errorMessage, which is the only place that says whether the run will retry, for example "Report run was interrupted after some notifications were sent. The report will not automatically retry." Could it still show when it differs from the channels' errors?
…alert and report runs once after send errors - `from_name` is required, and `tls_mode: none` needs host access (Rill Developer). - `SendTestEmail` only checks DMARC, inlined into its response; SPF applies to the envelope sender, which most providers set to their own domain. Duplicate DMARC records are an error. - Port 465 handshake failures report the TLS step; connecting, encrypting and logging in time out after 30s. - A cancelled send keeps its SMTP step, so reports only count as interrupted after an email may have arrived. Report runs that will retry aren't saved, so the retry isn't skipped. - Alerts record channel setup errors and cancellations after a send on the delivery and save the check once. - `AsEmailSender` is a `Handle` method again; `EmailClient` drops the unused connector parameter. - Mailpit tests skip in short mode.
… and report history shows a run's own error - The "use for all emails" option stays off until the project's email connector is known, and saving with it on waits for it. - Fields are locked once the connector file is saved, since saving again only retries the rill.yaml update. - The rill.yaml value is quoted when YAML would read it as another type, such as `null`. - The password is removed from .env again when the runtime refuses the connector file. - The Microsoft 365 preset is removed: Exchange Online doesn't offer PLAIN auth. - Test results show the DMARC policy and point to the test email's Authentication-Results header instead of checking SPF. - A report run with deliveries shows its error when it says more than the channels' errors, such as an interrupted run.
|
|
||
| // A run that will be retried is discarded (see executeAll). | ||
| // Saving it would make the retry skip its report time, which would already be the previous watermark. | ||
| if retry { |
There was a problem hiding this comment.
Sorry for the back and forth on this one. My earlier suggestion to stop saving runs that will retry missed a case: retry is also set for context.DeadlineExceeded, which comes from the report's own timeout rather than from the controller. Nothing reschedules these runs: Reconcile returns without advancing NextRunOn or setting a Retrigger, which was already true on main. Now that the run isn't saved, the timeout no longer appears in the history. The next unrelated reconcile, such as a deploy, sends the report late, and a report that always times out never records anything. Retrying only on context.Canceled, and recording DeadlineExceeded as a failed run, would fix this.
Developed in collaboration with Claude Code
There was a problem hiding this comment.
Good catch, fixed in 2903942 with a test for the timeout.
… of waiting for a retry
Report and alert emails can now go out through the project's own SMTP server, so they come from its domain instead of Rill's. Each commit is one step and can be reviewed on its own.
smtpconnector driver (host,port,username,password,tls_mode,from,from_name). Settingemail_connectorinrill.yamlsends every report and alert email of the project through it.Runtime.EmailClientpicks the sender: a connector passed by the caller (for notification templates later), thenemail_connector, then Rill's sender. A failing connector fails the run instead of falling back to Rill's sender, and Rill's internal BCC never goes through a customer connector.NotificationDeliveryper channel (connector, recipients, sent count, error). Slack still sends when email fails. Failed report runs are no longer recorded twice in the execution history.SendTestEmailsends a test email through a saved connector or unsaved properties, and reports the failed SMTP step, the latency, and the From domain's SPF and DMARC records..env, and can setemail_connector. SMTP connector files get a side panel with connection status, what sends through them, and a test send.Open questions:
from_namedefaults to "Rill", so projects that want no Rill marks have to set it.SendTestEmailwith unsaved properties lets a user who can edit the project make the runtime connect to any host and port. Should Cloud restrict private addresses or ports?Tested end to end with Mailpit as an SMTP server that requires a login, on a local Rill Cloud stack (admin, runtime, web-admin) and in Rill Developer:
Rill Developer: the connector form and side panel
Add → More → Email connector:
Provider presets fill the host, port and encryption:
A test send before saving names the failed step and a fix, and checks the From domain's SPF and DMARC records:
The saved connector references the password in
.env. The side panel shows the connection status and that nothing sends through it yet:The project's email connector, with a test email the server accepted:
Rill Cloud: emails delivered through the connector
Run now on a report; the run history shows the email channel:
The inbox, with report and alert emails from the connector's sender:
Rill Cloud: delivery failures (wrong SMTP password)
Checklist: