Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

feat(dashboard): set a custom subject on dashboard subscription emails (#83915)

Aleksandr Lesnenkoefb8835babd5
diff --git a/e2e/test/scenarios/sharing/sharing-reproductions.cy.spec.js b/e2e/test/scenarios/sharing/sharing-reproductions.cy.spec.js
index 29bf350fef6..58e24aca069 100644
--- a/e2e/test/scenarios/sharing/sharing-reproductions.cy.spec.js
+++ b/e2e/test/scenarios/sharing/sharing-reproductions.cy.spec.js
@@ -45,7 +45,7 @@ describe("issue 18009", { tags: "@external" }, () => {
// Click anywhere to close the popover that covers the "Send email now" button
// eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("To:").click();
+ cy.findByText("To").click();
H.sendEmailAndAssert((email) => {
expect(email.html).not.to.include(
@@ -114,7 +114,7 @@ describe("issues 18344 and 18352", { tags: "@external" }, () => {
cy.findByText(`${first_name} ${last_name}`).click();
// Click this just to close the popover that is blocking the "Send email now" button
// eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("To:").click();
+ cy.findByText("To").click();
H.sendEmailAndAssert(({ html }) => {
expect(html).not.to.include(
@@ -969,7 +969,7 @@ describe("issue 49525", { tags: "@external" }, () => {
H.popover().findByText(`${first_name} ${last_name}`).click();
// Click this just to close the popover that is blocking the "Send email now" button
- H.sidebar().findByText("To:").click();
+ H.sidebar().findByText("To").click();
H.clickSend();
cy.request("GET", `http://localhost:${WEB_PORT}/email`).then(({ body }) => {
diff --git a/e2e/test/scenarios/sharing/subscriptions.cy.spec.js b/e2e/test/scenarios/sharing/subscriptions.cy.spec.js
index 9a3517090b9..e032e5fb9f3 100644
--- a/e2e/test/scenarios/sharing/subscriptions.cy.spec.js
+++ b/e2e/test/scenarios/sharing/subscriptions.cy.spec.js
@@ -469,7 +469,7 @@ describe("scenarios > dashboard > subscriptions", () => {
it("should not display 'null' day of the week (metabase#14405)", () => {
assignRecipient();
- H.sidebar().findByText("To:").click();
+ H.sidebar().findByText("To").click();
cy.findByTestId("select-frequency").click();
H.popover().findByText("monthly").click();
diff --git a/frontend/src/metabase-types/api/notification-channels.ts b/frontend/src/metabase-types/api/notification-channels.ts
index ef693744045..256585a2acc 100644
--- a/frontend/src/metabase-types/api/notification-channels.ts
+++ b/frontend/src/metabase-types/api/notification-channels.ts
@@ -99,9 +99,18 @@ export interface ChannelApiResponse {
export type ChannelType = keyof ChannelApiResponse["channels"];
+export type PulseChannelDetails = {
+ channel?: string;
+ channel_id?: string;
+ subject?: string;
+ include_pdf?: boolean;
+ attachment_only?: boolean;
+ [specFieldName: string]: string | boolean | undefined;
+};
+
export type Channel = {
channel_type: ChannelType;
- details?: Record<string, string | boolean>;
+ details?: PulseChannelDetails;
enabled?: boolean;
recipients?: User[];
channel_id?: number;
diff --git a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/AddEditSidebar/AddEditEmailSidebar.tsx b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/AddEditSidebar/AddEditEmailSidebar.tsx
index 34a5c7ef1db..a02108e843a 100644
--- a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/AddEditSidebar/AddEditEmailSidebar.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/AddEditSidebar/AddEditEmailSidebar.tsx
@@ -21,7 +21,15 @@ import { channelTargetIsValid, dashboardPulseIsValid } from "metabase/pulse";
import { useSelector } from "metabase/redux";
import { getApplicationName } from "metabase/selectors/whitelabel";
import { getSetting } from "metabase/settings";
-import { Icon, Stack, Switch, Text, Title } from "metabase/ui";
+import {
+ Icon,
+ Input,
+ Stack,
+ Switch,
+ Text,
+ TextInput,
+ Title,
+} from "metabase/ui";
import type { UiParameter } from "metabase-lib/v1/parameters/types";
import {
type Channel,
@@ -41,6 +49,8 @@ import { DeleteSubscriptionAction } from "./DeleteSubscriptionAction";
import { EmailAttachmentPicker } from "./EmailAttachmentPicker";
import { getSubscriptionScheduleDescription } from "./utils";
+const SUBJECT_MAX_LENGTH = 255;
+
interface AddEditEmailSidebarProps {
pulse: DraftDashboardSubscription;
formInput: ChannelApiResponse;
@@ -131,7 +141,7 @@ export const AddEditEmailSidebar = ({
>
{isEmbeddingSdk() ? null : (
<div>
- <div className={CS.mb1}>{t`To:`}</div>
+ <Input.Label>{t`To`}</Input.Label>
<RecipientPicker
autoFocus={false}
recipients={channel.recipients}
@@ -147,6 +157,19 @@ export const AddEditEmailSidebar = ({
/>
</div>
)}
+ <TextInput
+ mt="lg"
+ label={t`Subject`}
+ placeholder={dashboard.name}
+ value={channel.details?.subject ?? ""}
+ maxLength={SUBJECT_MAX_LENGTH}
+ onChange={({ target: { value } }) =>
+ onChannelPropertyChange("details", {
+ ...channel.details,
+ subject: value.trim() ? value : undefined,
+ })
+ }
+ />
<Schedule
mt="lg"
value={_.pick(
diff --git a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/PulsesListSidebar.tsx b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/PulsesListSidebar.tsx
index 55f910a7eb5..952ee34ecf8 100644
--- a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/PulsesListSidebar.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/PulsesListSidebar.tsx
@@ -10,7 +10,16 @@ import { formatDateValue } from "metabase/parameters/utils/date-formatting";
import { getActivePulseParameters } from "metabase/pulse";
import { connect } from "metabase/redux";
import type { State } from "metabase/redux/store";
-import { Button, Card, Flex, Icon, Tooltip } from "metabase/ui";
+import {
+ Button,
+ Card,
+ Flex,
+ Group,
+ Icon,
+ Stack,
+ Text,
+ Tooltip,
+} from "metabase/ui";
import { conjunct } from "metabase/utils/formatting";
import { formatFrame } from "metabase/utils/time-dayjs";
import { isNotNull } from "metabase/utils/types";
@@ -24,6 +33,7 @@ import type {
ChannelApiResponse,
ChannelType,
DashboardSubscription,
+ IconName,
} from "metabase-types/api";
import { getParameters } from "../../selectors";
@@ -171,6 +181,14 @@ function canEditPulse(
}
}
+function getEmailSubject({
+ channels: [firstChannel],
+}: DashboardSubscription): string {
+ return firstChannel.channel_type === "email"
+ ? (firstChannel.details?.subject ?? "")
+ : "";
+}
+
function buildRecipientText(pulse: DashboardSubscription): string {
const {
channels: [firstChannel],
@@ -246,84 +264,52 @@ type PulseDetailsProps = {
};
function PulseDetails({ pulse, parameters }: PulseDetailsProps) {
- const recipientText = buildRecipientText(pulse);
- const filterText = buildFilterText(pulse, parameters);
+ const items: PulseDetailsItemProps[] = [
+ { icon: "string", text: getEmailSubject(pulse) },
+ { icon: "group", text: buildRecipientText(pulse) },
+ { icon: "filter", text: buildFilterText(pulse, parameters) },
+ ];
return (
- <div className={cx(CS.textMedium, CS.hoverChild)}>
- <ul
- className={cx(
- CS.flex,
- CS.flexColumn,
- CS.scrollX,
- CS.scrollY,
- CS.textUnspaced,
- )}
- style={{ maxHeight: 130 }}
+ <Stack
+ component="ul"
+ gap="sm"
+ mah={130}
+ className={cx(CS.scrollX, CS.scrollY)}
+ >
+ {items
+ .filter(({ text }) => text !== "")
+ .map(({ icon, text }) => (
+ <PulseDetailsItem key={icon} icon={icon} text={text} />
+ ))}
+ </Stack>
+ );
+}
+
+type PulseDetailsItemProps = {
+ icon: IconName;
+ text: string;
+};
+
+function PulseDetailsItem({ icon, text }: PulseDetailsItemProps) {
+ return (
+ <Group component="li" gap="sm" align="flex-start" wrap="nowrap" mr="sm">
+ <Icon
+ name={icon}
+ size={12}
+ c="text-secondary"
+ className={CS.hoverChild}
+ />
+ <Text
+ component="span"
+ size="sm"
+ fw="bold"
+ c="text-secondary"
+ className={CS.hoverChild}
>
- {recipientText && (
- <li
- className={cx(
- CS.flex,
- CS.alignStart,
- CS.mr1,
- CS.textBold,
- CS.textMedium,
- CS.hoverChild,
- CS.hoverInherit,
- )}
- >
- <Icon
- name="group"
- className={cx(CS.textMedium, CS.hoverChild, CS.hoverInherit)}
- size={12}
- />
- <span
- className={cx(
- CS.ml1,
- CS.textMedium,
- CS.hoverChild,
- CS.hoverInherit,
- )}
- style={{ fontSize: "12px" }}
- >
- {recipientText}
- </span>
- </li>
- )}
- {filterText && (
- <li
- className={cx(
- CS.flex,
- CS.alignStart,
- CS.mt1,
- CS.mr1,
- CS.textBold,
- CS.textMedium,
- CS.hoverChild,
- CS.hoverInherit,
- )}
- >
- <Icon
- name="filter"
- className={cx(CS.textMedium, CS.hoverChild, CS.hoverInherit)}
- size={12}
- />
- <span
- className={cx(
- CS.ml1,
- CS.textMedium,
- CS.hoverChild,
- CS.hoverInherit,
- )}
- style={{ fontSize: "12px" }}
- >
- {filterText}
- </span>
- </li>
- )}
- </ul>
- </div>
+ {text}
+ </Text>
+ </Group>
);
}
diff --git a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/PulsesListSidebar.unit.spec.tsx b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/PulsesListSidebar.unit.spec.tsx
index 3d47f3d69f8..fca01591180 100644
--- a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/PulsesListSidebar.unit.spec.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/PulsesListSidebar.unit.spec.tsx
@@ -1,11 +1,14 @@
+import { renderWithProviders, screen } from "__support__/ui";
import { createMockUiParameter } from "metabase-lib/v1/parameters/mock";
-import type { ParameterValueOrArray } from "metabase-types/api";
+import type { Channel, ParameterValueOrArray } from "metabase-types/api";
import {
+ createMockChannel,
createMockDashboardSubscription,
createMockParameter,
+ createMockUser,
} from "metabase-types/api/mocks";
-import { buildFilterText } from "./PulsesListSidebar";
+import { PulsesListSidebar, buildFilterText } from "./PulsesListSidebar";
jest.mock("metabase/parameters/utils/date-formatting", () => ({
formatDateValue: jest.fn((_parameter, value) =>
@@ -93,3 +96,40 @@ describe("buildFilterText", () => {
);
});
});
+
+describe("PulsesListSidebar", () => {
+ const setup = (channel: Channel) => {
+ renderWithProviders(
+ <PulsesListSidebar
+ pulses={[
+ createMockDashboardSubscription({ id: 1, channels: [channel] }),
+ ]}
+ formInput={{ channels: {} }}
+ createSubscription={jest.fn()}
+ onCancel={jest.fn()}
+ editPulse={jest.fn()}
+ />,
+ );
+ };
+
+ const recipient = createMockUser({ common_name: "Ada Lovelace" });
+
+ it("shows the custom subject of an email subscription", () => {
+ setup(
+ createMockChannel({
+ recipients: [recipient],
+ details: { subject: "Weekly revenue" },
+ }),
+ );
+
+ expect(screen.getByText("Weekly revenue")).toBeInTheDocument();
+ expect(screen.getByText("Ada Lovelace")).toBeInTheDocument();
+ });
+
+ it("shows only the recipients when no subject is set", () => {
+ setup(createMockChannel({ recipients: [recipient] }));
+
+ expect(screen.getAllByRole("listitem")).toHaveLength(1);
+ expect(screen.getByRole("listitem")).toHaveTextContent("Ada Lovelace");
+ });
+});
diff --git a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/tests/common.unit.spec.ts b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/tests/common.unit.spec.ts
index f95be603927..b0a65e5c4d8 100644
--- a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/tests/common.unit.spec.ts
+++ b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/tests/common.unit.spec.ts
@@ -1,8 +1,12 @@
import userEvent from "@testing-library/user-event";
import fetchMock from "fetch-mock";
-import { screen, within } from "__support__/ui";
+import { screen, waitFor, within } from "__support__/ui";
import type { DashboardSubscription } from "metabase-types/api";
+import {
+ createMockChannel,
+ createMockDashboardSubscription,
+} from "metabase-types/api/mocks";
import {
dashcard,
@@ -416,5 +420,84 @@ describe("DashboardSubscriptionsSidebar", () => {
const payload = await lastCall?.request?.json();
expect(payload.channels[0].details.include_pdf).toBe(true);
});
+
+ describe("subject", () => {
+ const selectRecipient = async () => {
+ await userEvent.click(
+ await screen.findByPlaceholderText(
+ "Enter user names or email addresses",
+ ),
+ );
+ await userEvent.click(
+ await screen.findByText(`${user.first_name} ${user.last_name}`),
+ );
+ };
+
+ it("should use the dashboard name as the placeholder", async () => {
+ setup();
+
+ await userEvent.click(await screen.findByText("Email it"));
+
+ expect(await screen.findByLabelText("Subject")).toHaveAttribute(
+ "placeholder",
+ "Dashboard",
+ );
+ });
+
+ it("should send the typed subject when creating a subscription", async () => {
+ setup();
+
+ await userEvent.click(await screen.findByText("Email it"));
+ await selectRecipient();
+ await userEvent.type(
+ await screen.findByLabelText("Subject"),
+ "Weekly revenue",
+ );
+ await userEvent.click(screen.getByRole("button", { name: "Done" }));
+
+ await waitFor(() =>
+ expect(
+ fetchMock.callHistory.called("path:/api/pulse", {
+ method: "POST",
+ }),
+ ).toBe(true),
+ );
+ const lastCall = fetchMock.callHistory.lastCall("path:/api/pulse", {
+ method: "POST",
+ });
+ const payload = await lastCall?.request?.json();
+ expect(payload.channels[0].details.subject).toBe("Weekly revenue");
+ });
+
+ it("should drop the subject when it is cleared on an existing subscription", async () => {
+ const pulse = createMockDashboardSubscription({
+ id: 10,
+ channels: [
+ createMockChannel({
+ schedule_type: "hourly",
+ recipients: [user],
+ details: { subject: "Weekly revenue" },
+ }),
+ ],
+ });
+ fetchMock.put("path:/api/pulse/10", pulse);
+ setup({ pulses: [pulse] });
+
+ await userEvent.click(await screen.findByText("Emailed hourly"));
+ const subjectInput = await screen.findByLabelText("Subject");
+ expect(subjectInput).toHaveValue("Weekly revenue");
+
+ await userEvent.clear(subjectInput);
+ await userEvent.click(screen.getByRole("button", { name: "Done" }));
+
+ await waitFor(() =>
+ expect(fetchMock.callHistory.called("path:/api/pulse/10")).toBe(true),
+ );
+ const lastCall = fetchMock.callHistory.lastCall("path:/api/pulse/10");
+ const payload = await lastCall?.request?.json();
+ expect(payload.channels[0].channel_type).toBe("email");
+ expect(payload.channels[0].details).not.toHaveProperty("subject");
+ });
+ });
});
});
diff --git a/frontend/src/metabase/notifications/channels/SlackChannelField.tsx b/frontend/src/metabase/notifications/channels/SlackChannelField.tsx
index 007544f5867..51ac86213a1 100644
--- a/frontend/src/metabase/notifications/channels/SlackChannelField.tsx
+++ b/frontend/src/metabase/notifications/channels/SlackChannelField.tsx
@@ -10,7 +10,11 @@ import {
import { useSelector } from "metabase/redux";
import { getApplicationName } from "metabase/selectors/whitelabel";
import { Autocomplete } from "metabase/ui";
-import type { Channel, ChannelSpec } from "metabase-types/api";
+import type {
+ Channel,
+ ChannelSpec,
+ PulseChannelDetails,
+} from "metabase-types/api";
const CHANNEL_FIELD_NAME = "channel";
const CHANNEL_PREFIX = "#";
@@ -21,10 +25,7 @@ const ALLOWED_PREFIXES = [CHANNEL_PREFIX, USER_PREFIX];
interface SlackChannelFieldProps {
channel: Channel;
channelSpec: ChannelSpec;
- onChannelPropertyChange: (
- key: string,
- value: Record<string, string | boolean>,
- ) => void;
+ onChannelPropertyChange: (key: string, value: PulseChannelDetails) => void;
}
export const SlackChannelField = ({
diff --git a/src/metabase/channel/impl/email.clj b/src/metabase/channel/impl/email.clj
index ed0248421e2..716d7485f05 100644
--- a/src/metabase/channel/impl/email.clj
+++ b/src/metabase/channel/impl/email.clj
@@ -221,7 +221,7 @@
(def ^:private payload-type->default-template
{:notification/dashboard {:channel_type :channel/email
:details {:type :email/handlebars-resource
- :subject "{{payload.dashboard.name}}"
+ :subject "{{computed.subject}}"
:path "dashboard_subscription"}}
:notification/card {:channel_type :channel/email
:details {:type :email/handlebars-resource
@@ -302,7 +302,7 @@
nil)))
(mu/defmethod channel/render-notification [:channel/email :notification/dashboard] :- [:sequential EmailMessage]
- [_channel-type {:keys [payload payload_type creator_id] :as notification-payload} {:keys [template recipients attachment_only include_pdf]}]
+ [_channel-type {:keys [payload payload_type creator_id] :as notification-payload} {:keys [template recipients attachment_only include_pdf subject]}]
(let [{:keys [dashboard_parts
dashboard_subscription
parameters
@@ -349,7 +349,8 @@
"<p>Dashboard content available in attached files</p>")
message-context-fn (fn [non-user-email]
(-> notification-payload
- (assoc :computed {:dashboard_content dashboard-content
+ (assoc :computed {:subject (or subject (:name dashboard))
+ :dashboard_content dashboard-content
:icon_cid (:content-id icon-attachment)
:dashboard_has_tabs (some-> dashboard :tabs seq)
:management_text (if (nil? non-user-email)
diff --git a/src/metabase/notification/payload/core.clj b/src/metabase/notification/payload/core.clj
index 7b508963de7..60e90ab9fca 100644
--- a/src/metabase/notification/payload/core.clj
+++ b/src/metabase/notification/payload/core.clj
@@ -54,7 +54,8 @@
[:template {:optional true} [:maybe ::models.channel/ChannelTemplate]]
[:recipients {:optional true} [:sequential ::models.notification/NotificationRecipient]]
[:attachment_only {:optional true} [:maybe :boolean]]
- [:include_pdf {:optional true} [:maybe :boolean]]]]]]]
+ [:include_pdf {:optional true} [:maybe :boolean]]
+ [:subject {:optional true} [:maybe :string]]]]]]]
[:payload_id {:optional true} [:maybe ms/PositiveInt]]])
(def ^:private NotificationBase
diff --git a/src/metabase/pulse/api/pulse.clj b/src/metabase/pulse/api/pulse.clj
index 12e88cb586a..a31c9fda14e 100644
--- a/src/metabase/pulse/api/pulse.clj
+++ b/src/metabase/pulse/api/pulse.clj
@@ -23,6 +23,7 @@
[metabase.pulse.db :as pulse.db]
[metabase.pulse.models.pulse :as models.pulse]
[metabase.pulse.models.pulse-channel :as pulse-channel]
+ [metabase.pulse.schema :as pulse.schema]
[metabase.pulse.send :as pulse.send]
[metabase.util :as u]
[metabase.util.i18n :refer [tru]]
@@ -130,6 +131,7 @@
[:map {:closed true}
[:attachment_only {:optional true} [:maybe :boolean]]
[:include_pdf {:optional true} [:maybe :boolean]]
+ [:subject {:optional true} [:maybe ::pulse.schema/email-subject]]
[:channel {:optional true} [:maybe :string]]
[:channels {:optional true} [:maybe :string]]
[:channel_id {:optional true} [:maybe :string]]
diff --git a/src/metabase/pulse/schema.clj b/src/metabase/pulse/schema.clj
index 3a2c9b293b4..bc114f2d263 100644
--- a/src/metabase/pulse/schema.clj
+++ b/src/metabase/pulse/schema.clj
@@ -58,9 +58,21 @@
[:format_rows {:optional true} [:maybe :boolean]]
[:pivot_results {:optional true} [:maybe :boolean]]])
+(def ^:private subject-max-length
+ "Inboxes truncate long before this; it bounds what a client can store."
+ 255)
+
+(mr/def ::email-subject
+ "A dashboard subscription email subject: one line, not blank, at most 255 characters."
+ [:and
+ ms/NonBlankString
+ [:string {:max subject-max-length}]
+ ;; the value becomes a mail header, so a line break would let it inject headers
+ [:re {:error/message "a single line"} #"\A[^\r\n]*\z"]])
+
(mr/def ::pulse-channel.details
"The `:details` column of a PulseChannel, decoded. Shape varies by `:channel_type` (email carries
- `:emails`; slack carries `:channel`/`:channels`/`:channel_id`; both may carry `:include_pdf`/
+ `:emails` and `:subject`; slack carries `:channel`/`:channels`/`:channel_id`; both may carry `:include_pdf`/
`:attachment_only`), so every key is optional here rather than modeled as a `:channel_type`-dispatched
`:multi`."
[:map {:closed true}
@@ -69,6 +81,7 @@
[:channel_id {:optional true} [:maybe :string]]
[:include_pdf {:optional true} [:maybe :boolean]]
[:attachment_only {:optional true} [:maybe :boolean]]
+ [:subject {:optional true} [:maybe ::email-subject]]
[:emails {:optional true} [:maybe [:sequential :string]]]])
(mr/def ::pulse-channel
diff --git a/src/metabase/pulse/send.clj b/src/metabase/pulse/send.clj
index 1f63a041bab..f9707c5bb4f 100644
--- a/src/metabase/pulse/send.clj
+++ b/src/metabase/pulse/send.clj
@@ -2,6 +2,7 @@
"Code related to sending Pulses (Alerts or Dashboard Subscriptions)."
(:require
[clojure.string :as str]
+ [medley.core :as m]
[metabase.models.interface :as mi]
[metabase.notification.core :as notification]
[metabase.pulse.db :as pulse.db]
@@ -81,7 +82,9 @@
:dashboard_card_id (:dashboard_card_id %)}
(select-keys % [:include_xls :include_csv :pivot_results :format_rows]))
(:cards pulse))}
- :handlers [(get-notification-handler pulse-channel)]}
+ ;; only a dashboard subscription email has a subject; an alert handler must not carry the key
+ :handlers [(m/assoc-some (get-notification-handler pulse-channel)
+ :subject (get-in pulse-channel [:details :subject]))]}
{:id (:id pulse)
:payload_type :notification/card
:creator_id (:creator_id pulse)
diff --git a/test/metabase/pulse/api/pulse_test.clj b/test/metabase/pulse/api/pulse_test.clj
index c8b371c421b..642803e4dea 100644
--- a/test/metabase/pulse/api/pulse_test.clj
+++ b/test/metabase/pulse/api/pulse_test.clj
@@ -206,6 +206,39 @@
:schedule_type "hourly"
:details {:channels "#general"}})
+(deftest create-pulse-rejects-bad-email-subject-test
+ (testing "POST /api/pulse rejects an email subject that is blank, too long, or more than one line"
+ (doseq [subject [" "
+ (apply str (repeat 256 "a"))
+ "Weekly KPIs\nBcc: [email protected]"
+ "Weekly KPIs\r"]]
+ (testing (pr-str subject)
+ (is (=? {:specific-errors {:channels some?}}
+ (mt/user-http-request :rasta :post 400 "pulse"
+ {:name "abc"
+ :cards [{:id 100, :include_csv false, :include_xls false, :dashboard_card_id nil}]
+ :channels [(assoc daily-email-channel :details {:subject subject})]})))))))
+
+(deftest create-pulse-with-email-subject-test
+ (testing "POST /api/pulse stores an email subject that GET /api/pulse/:id returns"
+ (mt/with-temp [:model/Collection collection {}
+ :model/Card card {}
+ :model/Dashboard dashboard {:name "Birdcage KPIs" :collection_id (u/the-id collection)}]
+ (api.card-test/with-cards-in-readable-collection! [card]
+ (mt/with-model-cleanup [:model/Pulse]
+ (let [{pulse-id :id} (mt/user-http-request :rasta :post 200 "pulse"
+ {:name "Birdcage KPIs"
+ :collection_id (u/the-id collection)
+ :dashboard_id (u/the-id dashboard)
+ :cards [{:id (u/the-id card)
+ :include_csv false
+ :include_xls false
+ :dashboard_card_id nil}]
+ :channels [(assoc daily-email-channel
+ :details {:subject "Birdcage KPIs, Account A"})]})]
+ (is (=? {:channels [{:details {:subject "Birdcage KPIs, Account A"}}]}
+ (mt/user-http-request :rasta :get 200 (str "pulse/" pulse-id))))))))))
+
(deftest create-test
(testing "POST /api/pulse"
(testing "legacy pulse"
@@ -1064,6 +1097,29 @@
:recipient-type nil}
(mt/summarize-multipart-single-email (-> channel-messages :channel/email first) #"Daily Sad Toucans")))))))))))
+(deftest send-test-pulse-custom-subject-test
+ (testing "POST /api/pulse/test sends the email with the channel's custom subject (#63305)"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-fake-inbox
+ (mt/with-temp [:model/Collection collection {}
+ :model/Dashboard {dashboard-id :id} {:name "Daily Sad Toucans"}
+ :model/Card card {:dataset_query (mt/mbql-query venues {:aggregation [[:count]]})}]
+ (perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
+ (api.card-test/with-cards-in-readable-collection! [card]
+ (let [channel-messages (pulse.test-util/with-captured-channel-send-messages!
+ (mt/user-http-request :rasta :post 200 "pulse/test"
+ {:name (mt/random-name)
+ :dashboard_id dashboard-id
+ :cards [{:id (:id card)
+ :include_csv false
+ :include_xls false
+ :dashboard_card_id nil}]
+ :channels [(assoc daily-email-channel
+ :details {:subject "Sad Toucans, Account A"}
+ :recipients [(mt/fetch-user :rasta)])]}))]
+ (is (= "Sad Toucans, Account A"
+ (-> channel-messages :channel/email first :subject))))))))))
+
(deftest send-test-pulse-to-non-user-test
(testing "sending test email to non user won't include unsubscribe link (#43391)"
(mt/with-non-admin-groups-no-root-collection-perms
diff --git a/test/metabase/pulse/dashboard_subscription_test.clj b/test/metabase/pulse/dashboard_subscription_test.clj
index 9ad26f1a0ce..a8de6b95b3b 100644
--- a/test/metabase/pulse/dashboard_subscription_test.clj
+++ b/test/metabase/pulse/dashboard_subscription_test.clj
@@ -1786,6 +1786,47 @@
(first (:channel/email pulse-results))
#"Aviary KPIs")))))))))
+(defn- send-email-dashsub-with-details!
+ "Send a one-card dashboard subscription named \"Aviary KPIs\" to rasta over an email channel with `details`, and
+ return the captured email."
+ [details]
+ (mt/with-temp [:model/Card {card-id :id} {:name pulse.test-util/card-name
+ :dataset_query (mt/mbql-query orders {:limit 1})}
+ :model/Dashboard {dashboard-id :id} {:name "Aviary KPIs"}
+ :model/DashboardCard _ {:dashboard_id dashboard-id
+ :card_id card-id}
+ :model/Pulse {pulse-id :id} {:name "Pulse Name"
+ :dashboard_id dashboard-id}
+ :model/PulseCard _ {:pulse_id pulse-id
+ :card_id card-id
+ :position 0}
+ :model/PulseChannel {pc-id :id} {:pulse_id pulse-id
+ :channel_type "email"
+ :details details}
+ :model/PulseChannelRecipient _ {:user_id (pulse.test-util/rasta-id)
+ :pulse_channel_id pc-id}]
+ (-> (pulse.test-util/with-captured-channel-send-messages!
+ (pulse.send/send-pulse! (t2/select-one :model/Pulse pulse-id)))
+ :channel/email
+ first)))
+
+(deftest dashboard-sub-custom-subject-test
+ (testing "An email channel with :subject sends it as the subject and keeps the dashboard name in the body (#63305)"
+ (is (= (rasta-dashsub-message {:subject "Aviary KPIs, Account A"})
+ (mt/summarize-multipart-single-email
+ (send-email-dashsub-with-details! {:subject "Aviary KPIs, Account A"})
+ #"Aviary KPIs")))))
+
+(deftest dashboard-sub-custom-subject-is-literal-test
+ (testing "Template syntax in a custom subject is sent as typed, not resolved against the payload"
+ (is (= "{{payload.dashboard.id}} report"
+ (:subject (send-email-dashsub-with-details! {:subject "{{payload.dashboard.id}} report"}))))))
+
+(deftest dashboard-sub-without-subject-uses-dashboard-name-test
+ (testing "An email channel without :subject keeps the dashboard name as the subject"
+ (is (= "Aviary KPIs"
+ (:subject (send-email-dashsub-with-details! {}))))))
+
(deftest dashboard-sub-slack-include-pdf-test
(testing "A Slack channel with :include_pdf renders the dashboard PDF and carries it on the message"
(notification.tu/with-channel-fixtures [:channel/slack]