}
+ */
+async function emitProviderTemplateEvent(strapi, name, payload) {
+ try {
+ if (!strapi.eventHub || typeof strapi.eventHub.emit !== 'function') return;
+ await strapi.eventHub.emit(`magic-mail.provider-template.${name}`, {
+ key: payload.key,
+ code: payload.code ?? null,
+ coreEmailType: payload.coreEmailType ?? null,
+ ...(payload.fallback ? { fallback: payload.fallback } : {}),
+ });
+ } catch (error) {
+ strapi.log?.warn?.(
+ `[magic-mail] Provider template event listener failed: ${error?.name || 'Error'}`
+ );
+ }
+}
+
+module.exports = { emitProviderTemplateEvent };
diff --git a/tests/admin/strict-mode.test.jsx b/tests/admin/strict-mode.test.jsx
index 233d9cc..edbf160 100644
--- a/tests/admin/strict-mode.test.jsx
+++ b/tests/admin/strict-mode.test.jsx
@@ -606,3 +606,75 @@ test('plugin settings page: the provider-tracking switch appears only with a tem
assert.equal(live(result.mountCalls, '/magic-mail/settings').length, 1);
assert.equal(mutations(result.calls).length, 0, 'no mutation');
});
+
+/** Core designs with the admin forgot-password row (RFC #27752). */
+const coreDesignsWithAdmin = ({ editable, broken = false }) => ({
+ ...Object.fromEntries(
+ Object.entries(CORE_DESIGNS).map(([type, design]) => [type, { ...design, editable: true }])
+ ),
+ 'admin-forgot-password': broken
+ ? {
+ ...CORE_DESIGNS['reset-password'],
+ mode: 'provider',
+ providerTemplate: 'sendgrid:admin-reset',
+ templateName: null,
+ provider: 'sendgrid',
+ status: 'missing',
+ usable: false,
+ problem: 'MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE',
+ checkedAt: '2026-11-19T08:00:00.000Z',
+ editable,
+ }
+ : { ...CORE_DESIGNS['reset-password'], editable },
+});
+
+test('core emails: the admin password reset row offers the design choice to super admins only', async () => {
+ for (const editable of [true, false]) {
+ providerRoutes();
+ network.on('GET', '/magic-mail/designer/core-designs', {
+ data: coreDesignsWithAdmin({ editable }),
+ });
+ const result = await checkStrictEntry(, {
+ path: '/plugins/magic-mail/designer',
+ permissions: ALL,
+ async whileMounted() {
+ await clickLabel('Core emails');
+ await wait(50);
+ assert.match(document.body.textContent, /Admin password reset/);
+ assert.match(document.body.textContent, /subject and body from Users & Permissions/);
+ assert.equal(button('Edit Admin password reset'), undefined, 'no local editor');
+ assert.ok(button('Edit Reset password'));
+ if (editable) {
+ await clickLabel('Choose design of Admin password reset');
+ assert.match(document.body.textContent, /Design of Admin password reset/);
+ await clickLabel('Close');
+ await wait(50);
+ } else {
+ assert.equal(button('Choose design of Admin password reset'), undefined);
+ assert.ok(button('Choose design of Reset password'));
+ }
+ },
+ });
+ assert.equal(mutations(result.calls).length, 0, 'no mutation');
+ }
+});
+
+test('dashboard: the core email alert names the admin mail with its reason and check time', async () => {
+ pluginRoutes();
+ network.on('GET', '/magic-mail/accounts', { data: [ACCOUNT, BREVO_ACCOUNT] });
+ network.on('GET', '/magic-mail/designer/core-designs', {
+ data: coreDesignsWithAdmin({ editable: true, broken: true }),
+ });
+ const result = await checkStrictEntry(, {
+ path: '/plugins/magic-mail',
+ permissions: ALL,
+ async whileMounted() {
+ await wait(50);
+ const alert = document.querySelector('[role="alert"]');
+ assert.ok(alert, 'alert is shown');
+ assert.match(alert.textContent, /Admin password reset \(deleted or unpublished/);
+ assert.match(alert.textContent, /Last checked:/);
+ },
+ });
+ assert.equal(mutations(result.calls).length, 0, 'no mutation');
+});
diff --git a/tests/core-mails-integration.test.js b/tests/core-mails-integration.test.js
new file mode 100644
index 0000000..e6d043a
--- /dev/null
+++ b/tests/core-mails-integration.test.js
@@ -0,0 +1,638 @@
+'use strict';
+
+// Core emails through provider templates (Strapi RFC #27752 gaps) against the
+// fake SendGrid and Mailgun servers: email confirmation end to end through
+// both providers, password reset and admin forgot password through Mailgun
+// and SendGrid, the SendGrid subject injection, the provider-template events
+// and the startup check. Synthetic data only; no request leaves 127.0.0.1.
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const {
+ createState,
+ redirectProviderFetch,
+ startFakeProviders,
+} = require('./helpers/fake-template-providers');
+const { createStrapi, quietLog } = require('./helpers/provider-template-strapi');
+const { encryptCredentials } = require('../server/src/utils/encryption');
+const bootstrap = require('../server/src/bootstrap');
+
+const { installEmailInterception, uninstallEmailInterception } = bootstrap;
+
+let fake;
+let state;
+let restoreFetch;
+let previousKey;
+
+test.before(async () => {
+ previousKey = process.env.MAGIC_MAIL_ENCRYPTION_KEY;
+ process.env.MAGIC_MAIL_ENCRYPTION_KEY = 'q'.repeat(32);
+ state = createState();
+ fake = await startFakeProviders(state);
+ restoreFetch = redirectProviderFetch(fake.port);
+});
+
+test.after(async () => {
+ restoreFetch();
+ await fake.close();
+ if (previousKey === undefined) delete process.env.MAGIC_MAIL_ENCRYPTION_KEY;
+ else process.env.MAGIC_MAIL_ENCRYPTION_KEY = previousKey;
+});
+
+function reset() {
+ const fresh = createState();
+ for (const key of Object.keys(fresh)) state[key] = fresh[key];
+}
+
+const sendgridAccount = (documentId) => ({
+ documentId,
+ name: documentId,
+ provider: 'sendgrid',
+ fromEmail: `noreply@${documentId}.example.test`,
+ fromName: 'Synthetic',
+ isActive: true,
+ priority: 5,
+ config: encryptCredentials({ apiKey: `SG.${documentId}` }),
+});
+
+const mailgunAccount = (documentId) => ({
+ documentId,
+ name: documentId,
+ provider: 'mailgun',
+ fromEmail: 'noreply@mg.example.test',
+ isActive: true,
+ priority: 4,
+ config: encryptCredentials({
+ apiKey: `key-${documentId}`,
+ domain: 'mg.example.test',
+ region: 'us',
+ }),
+});
+
+const sgTemplate = (id, name, subject = '{{subject}}') => ({
+ id,
+ name,
+ updated_at: '2026-11-10 08:30:00',
+ versions: [
+ {
+ id: `${id}-v1`,
+ template_id: id,
+ active: 1,
+ name: 'v1',
+ subject,
+ html_content: '{{url}}
',
+ plain_content: '{{url}}',
+ updated_at: '2026-11-11 09:00:00',
+ },
+ ],
+});
+
+const mgTemplate = (name) => ({
+ name,
+ id: `mg-${name}`,
+ createdAt: 'Mon, 10 Nov 2026 08:30:00 UTC',
+ version: {
+ tag: 'v1',
+ template: '{{url}}
',
+ engine: 'handlebars',
+ createdAt: 'Tue, 11 Nov 2026 09:00:00 UTC',
+ active: true,
+ id: `mg-${name}-v1`,
+ headers: { Subject: 'Synthetic subject' },
+ },
+});
+
+const sends = (host) =>
+ state.requests.filter(
+ (r) => r.host === host && r.method === 'POST' && /\/(mail\/send|messages)$/.test(r.path)
+ );
+
+const interpolate = (layout, data) =>
+ layout.replace(/<%=\s*([\w.]+)\s*%>/g, (_, path) =>
+ String(path.split('.').reduce((value, part) => value?.[part], data) ?? '')
+ );
+
+/** users-permissions template(): lodash-style <%= KEY %> interpolation. */
+function fakeUsersPermissions() {
+ const service = { template: (layout, data) => interpolate(layout, data) };
+ return { service: (name) => (name === 'users-permissions' ? service : null), _service: service };
+}
+
+/**
+ * @strapi/email 5.63 double: send() and sendTemplatedEmail() both end in
+ * provider.send(); sendTemplatedEmail renders subject/text/html first.
+ */
+function emailPluginDouble() {
+ const nativeSends = [];
+ const provider = {
+ send: async (options) => {
+ nativeSends.push(options);
+ return { messageId: 'native' };
+ },
+ };
+ const service = {
+ send: (options) => provider.send(options),
+ sendTemplatedEmail: (options, template, data) => {
+ const rendered = {};
+ for (const field of ['subject', 'text', 'html']) {
+ if (template[field]) rendered[field] = interpolate(template[field], data);
+ }
+ return provider.send({ ...options, ...rendered });
+ },
+ };
+ return { plugin: { provider, service: () => service }, service, nativeSends };
+}
+
+const ADMIN_URL = 'https://cms.example.test/admin';
+const SERVER_URL = 'https://cms.example.test';
+const ADMIN_TEMPLATE = Object.freeze({
+ subject: 'Reset password',
+ text: 'Reset your password: <%= url %>',
+ html: 'Reset your password: <%= url %>
',
+});
+const CONFIG = {
+ 'admin.absoluteUrl': ADMIN_URL,
+ 'server.absoluteUrl': SERVER_URL,
+ 'admin.forgotPassword.emailTemplate': ADMIN_TEMPLATE,
+ 'info.strapi': '5.63.0',
+};
+const SUPER_ADMIN = { id: 1, roles: [{ code: 'strapi-super-admin' }] };
+
+/** Mirrors @strapi/admin 5.63 services/auth.js forgotPassword(). */
+function adminForgotPassword(email, template = ADMIN_TEMPLATE) {
+ return email.service.sendTemplatedEmail(
+ { to: 'admin@example.test', from: undefined, replyTo: undefined },
+ template,
+ {
+ url: `${ADMIN_URL}/auth/reset-password?code=admintok42`,
+ user: { email: 'admin@example.test', firstname: 'Grace', lastname: 'Hopper', username: null },
+ }
+ );
+}
+
+/** Mirrors users-permissions 5.63 sendConfirmationEmail(). */
+function sendConfirmation(up, email) {
+ const data = {
+ URL: `${SERVER_URL}/api/auth/email-confirmation`,
+ SERVER_URL,
+ ADMIN_URL,
+ USER: {
+ id: 9,
+ documentId: 'user9',
+ email: 'new@example.test',
+ username: 'new.user',
+ confirmed: false,
+ },
+ CODE: 'conf123',
+ };
+ const message = up._service.template('Confirm: <%= URL %>?confirmation=<%= CODE %>
', data);
+ const subject = up._service.template('Account confirmation', { USER: data.USER });
+ return email.service.send({
+ to: 'new@example.test',
+ from: undefined,
+ replyTo: 'support@example.test',
+ subject,
+ text: message,
+ html: message,
+ });
+}
+
+/** Mirrors users-permissions 5.63 forgotPassword(). */
+function sendReset(up, email, baseUrl = 'https://app.example.test/reset') {
+ const data = {
+ URL: baseUrl,
+ SERVER_URL,
+ ADMIN_URL,
+ USER: { id: 7, email: 'user@example.test', username: 'user.seven' },
+ TOKEN: 'tok123',
+ };
+ const message = up._service.template('Reset: <%= URL %>?code=<%= TOKEN %>
', data);
+ return email.service.send({
+ to: 'user@example.test',
+ subject: 'Reset password',
+ text: message,
+ html: message,
+ });
+}
+
+/** A harness with interception installed for one provider account. */
+async function setup({ accounts, adminUser = { id: 3, preferedLanguage: 'de-AT' }, log } = {}) {
+ const up = fakeUsersPermissions();
+ const email = emailPluginDouble();
+ const db = {
+ query: (uid) => ({
+ findOne: async () => (uid === 'admin::user' ? adminUser : null),
+ }),
+ };
+ const h = createStrapi({
+ accounts,
+ emailPlugin: email.plugin,
+ usersPermissions: up,
+ config: CONFIG,
+ db,
+ ...(log ? { log } : {}),
+ });
+ installEmailInterception(h.strapi, log || quietLog);
+ await h.service('provider-templates').sync({ force: true });
+ return { h, up, email, service: h.service('provider-templates') };
+}
+
+// ─── Email confirmation end to end ────────────────────────────────────────
+
+test('email confirmation through a SendGrid template: v1 payload, no designer body', async () => {
+ reset();
+ state.sendgrid.us = [sgTemplate('d-confirm', 'Confirm email')];
+ const { h, up, email, service } = await setup({ accounts: [sendgridAccount('sg1')] });
+ try {
+ await service.setCoreDesign(
+ 'email-confirmation',
+ { providerTemplate: 'sendgrid:confirm-email' },
+ { id: 1 }
+ );
+ await sendConfirmation(up, email);
+ assert.equal(email.nativeSends.length, 0);
+ const json = sends('api.sendgrid.com')[0].json;
+ assert.equal(json.template_id, 'd-confirm');
+ assert.equal(json.content, undefined, 'no designer body');
+ assert.equal(json.subject, undefined, 'the users-permissions subject is not sent');
+ const data = json.personalizations[0].dynamic_template_data;
+ assert.equal(data.CODE, 'conf123');
+ assert.equal(data.code, 'conf123');
+ assert.equal(data.url, `${SERVER_URL}/api/auth/email-confirmation?confirmation=conf123`);
+ assert.deepEqual(data.user, { id: 9, email: 'new@example.test', username: 'new.user' });
+ assert.equal(data.subject, undefined, 'no subject is injected for core mails');
+ assert.deepEqual(data.meta, {
+ templateKey: 'sendgrid:confirm-email',
+ payloadVersion: 1,
+ coreEmailType: 'email-confirmation',
+ strapiVersion: '5.63.0',
+ });
+ assert.equal(json.reply_to.email, 'support@example.test', 'Reply-To from Strapi is kept');
+ assert.equal(json.from.email, 'noreply@sg1.example.test');
+ } finally {
+ uninstallEmailInterception(h.strapi);
+ }
+});
+
+test('email confirmation through a Mailgun template: template, t:variables, template subject', async () => {
+ reset();
+ state.mailgun.us.domains['mg.example.test'] = [mgTemplate('confirm-email')];
+ const { h, up, email, service } = await setup({ accounts: [mailgunAccount('mg1')] });
+ try {
+ await service.setCoreDesign(
+ 'email-confirmation',
+ { providerTemplate: 'mailgun:confirm-email' },
+ { id: 1 }
+ );
+ await sendConfirmation(up, email);
+ assert.equal(email.nativeSends.length, 0);
+ const form = Object.fromEntries(sends('api.mailgun.net')[0].form);
+ assert.equal(form.template, 'confirm-email');
+ assert.equal(form.subject, undefined, 'the Mailgun template Subject header is used');
+ assert.equal(form.html, undefined);
+ const vars = JSON.parse(form['t:variables']);
+ assert.equal(vars.url, `${SERVER_URL}/api/auth/email-confirmation?confirmation=conf123`);
+ assert.equal(vars.meta.coreEmailType, 'email-confirmation');
+ assert.equal(form['h:Reply-To'], 'support@example.test');
+ } finally {
+ uninstallEmailInterception(h.strapi);
+ }
+});
+
+// ─── Mailgun core path: password reset and admin forgot password ────────────
+
+test('Mailgun: password reset through the chosen template with the v1 payload', async () => {
+ reset();
+ state.mailgun.us.domains['mg.example.test'] = [mgTemplate('reset-password')];
+ const { h, up, email, service } = await setup({ accounts: [mailgunAccount('mg1')] });
+ try {
+ await service.setCoreDesign(
+ 'reset-password',
+ { providerTemplate: 'mailgun:reset-password' },
+ { id: 1 }
+ );
+ await sendReset(up, email);
+ const form = Object.fromEntries(sends('api.mailgun.net')[0].form);
+ assert.equal(form.template, 'reset-password');
+ const vars = JSON.parse(form['t:variables']);
+ assert.equal(vars.TOKEN, 'tok123');
+ assert.equal(vars.url, 'https://app.example.test/reset?code=tok123');
+ assert.deepEqual(vars.USER, { id: 7, email: 'user@example.test', username: 'user.seven' });
+ assert.equal(vars.meta.strapiVersion, '5.63.0');
+ } finally {
+ uninstallEmailInterception(h.strapi);
+ }
+});
+
+test('Mailgun: admin forgot password through the chosen template with payload v1', async () => {
+ reset();
+ state.mailgun.us.domains['mg.example.test'] = [mgTemplate('admin-reset')];
+ const { h, email, service } = await setup({ accounts: [mailgunAccount('mg1')] });
+ try {
+ await assert.rejects(
+ service.setCoreDesign(
+ 'admin-forgot-password',
+ { providerTemplate: 'mailgun:admin-reset' },
+ { id: 2, roles: [{ code: 'strapi-editor' }] }
+ ),
+ (error) => error.name === 'ForbiddenError'
+ );
+ await service.setCoreDesign(
+ 'admin-forgot-password',
+ { providerTemplate: 'mailgun:admin-reset' },
+ SUPER_ADMIN
+ );
+ await adminForgotPassword(email);
+ assert.equal(email.nativeSends.length, 0, 'Strapi did not render or send its own body');
+ const form = Object.fromEntries(sends('api.mailgun.net')[0].form);
+ assert.equal(form.template, 'admin-reset');
+ assert.equal(form.to, 'admin@example.test');
+ assert.equal(form.subject, undefined);
+ assert.deepEqual(JSON.parse(form['t:variables']), {
+ user: {
+ id: 3,
+ email: 'admin@example.test',
+ firstname: 'Grace',
+ lastname: 'Hopper',
+ },
+ url: `${ADMIN_URL}/auth/reset-password?code=admintok42`,
+ token: 'admintok42',
+ adminUrl: ADMIN_URL,
+ serverUrl: SERVER_URL,
+ meta: {
+ templateKey: 'mailgun:admin-reset',
+ payloadVersion: 1,
+ coreEmailType: 'admin-forgot-password',
+ locale: 'de-AT',
+ strapiVersion: '5.63.0',
+ },
+ });
+ } finally {
+ uninstallEmailInterception(h.strapi);
+ }
+});
+
+test('admin forgot password without a provider template: Strapi renders the local body as before', async () => {
+ reset();
+ state.sendgrid.us = [sgTemplate('d-admin', 'Admin reset')];
+ const { h, email } = await setup({ accounts: [sendgridAccount('sg1')] });
+ try {
+ await adminForgotPassword(email);
+ const json = sends('api.sendgrid.com')[0].json;
+ assert.equal(json.template_id, undefined);
+ assert.equal(json.subject, 'Reset password');
+ assert.match(json.content[1].value, /admintok42/);
+ } finally {
+ uninstallEmailInterception(h.strapi);
+ }
+});
+
+test('SendGrid: admin forgot password via template, strict error, opt-in Strapi fallback, events', async () => {
+ reset();
+ state.sendgrid.us = [sgTemplate('d-admin', 'Admin reset')];
+ const { h, email, service } = await setup({ accounts: [sendgridAccount('sg1')] });
+ try {
+ await service.setCoreDesign(
+ 'admin-forgot-password',
+ { providerTemplate: 'sendgrid:admin-reset' },
+ SUPER_ADMIN
+ );
+ await adminForgotPassword(email);
+ const data = sends('api.sendgrid.com')[0].json.personalizations[0].dynamic_template_data;
+ assert.equal(data.token, 'admintok42');
+ assert.equal(data.meta.coreEmailType, 'admin-forgot-password');
+
+ // The template disappears: strict by default, nothing else is sent.
+ state.sendgrid.us = [];
+ await service.sync({ force: true });
+ h.events.length = 0;
+ await assert.rejects(
+ adminForgotPassword(email),
+ (error) => error.code === 'MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE'
+ );
+ assert.equal(sends('api.sendgrid.com').length, 1);
+ assert.deepEqual(h.events, [
+ {
+ name: 'magic-mail.provider-template.failed',
+ payload: {
+ key: 'sendgrid:admin-reset',
+ code: 'MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE',
+ coreEmailType: 'admin-forgot-password',
+ },
+ },
+ ]);
+
+ // Opt-in fallback: the Strapi admin email is rendered and sent instead.
+ await service.setCoreDesign(
+ 'admin-forgot-password',
+ { providerTemplate: 'sendgrid:admin-reset', fallbackToDesigner: true },
+ SUPER_ADMIN
+ );
+ h.events.length = 0;
+ await adminForgotPassword(email);
+ const local = sends('api.sendgrid.com')[1].json;
+ assert.equal(local.template_id, undefined);
+ assert.equal(local.subject, 'Reset password');
+ assert.match(local.content[1].value, /admintok42/);
+ assert.deepEqual(
+ h.events.map((event) => event.name),
+ ['magic-mail.provider-template.failed', 'magic-mail.provider-template.fallback']
+ );
+ assert.deepEqual(h.events[1].payload, {
+ key: 'sendgrid:admin-reset',
+ code: 'MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE',
+ coreEmailType: 'admin-forgot-password',
+ fallback: 'designer',
+ });
+ const serialized = JSON.stringify(h.events);
+ assert.equal(serialized.includes('admin@example.test'), false, 'no addresses in events');
+ assert.equal(serialized.includes('admintok42'), false, 'no tokens in events');
+ } finally {
+ uninstallEmailInterception(h.strapi);
+ }
+});
+
+// ─── Missing url warning ─────────────────────────────────────────────────
+
+test('a core mail whose base URL is not absolute warns once and sends url ""', async () => {
+ reset();
+ state.sendgrid.us = [sgTemplate('d-reset', 'Reset password')];
+ const warnings = [];
+ const log = { ...quietLog, warn: (message) => warnings.push(String(message)) };
+ const { h, up, email, service } = await setup({ accounts: [sendgridAccount('sg1')], log });
+ try {
+ await service.setCoreDesign(
+ 'reset-password',
+ { providerTemplate: 'sendgrid:reset-password' },
+ { id: 1 }
+ );
+ await sendReset(up, email, 'null');
+ await sendReset(up, email, '/relative/reset');
+ const first = sends('api.sendgrid.com')[0].json.personalizations[0].dynamic_template_data;
+ assert.equal(first.url, '');
+ const urlWarnings = warnings.filter((message) => message.includes('"url" can not be built'));
+ assert.equal(urlWarnings.length, 1, 'warned once per process and core mail');
+ assert.match(urlWarnings[0], /reset-password/);
+ assert.equal(urlWarnings[0].includes('tok123'), false);
+ } finally {
+ uninstallEmailInterception(h.strapi);
+ }
+});
+
+// ─── SendGrid subject injection ────────────────────────────────────────────
+
+test('SendGrid: a passed subject becomes dynamic_template_data.subject unless data sets one', async () => {
+ reset();
+ state.sendgrid.us = [sgTemplate('d-news', 'News')];
+ const h = createStrapi({ accounts: [sendgridAccount('sg1')] });
+ await h.service('provider-templates').sync({ force: true });
+ const router = h.service('email-router');
+
+ await router.send({
+ to: 'a@example.test',
+ providerTemplate: 'sendgrid:news',
+ subject: 'Per-mail subject\r\nBcc: x@example.test',
+ data: { name: 'Ada' },
+ });
+ let json = sends('api.sendgrid.com')[0].json;
+ assert.deepEqual(json.personalizations[0].dynamic_template_data, {
+ name: 'Ada',
+ subject: 'Per-mail subjectBcc: x@example.test',
+ });
+
+ await router.send({
+ to: 'a@example.test',
+ providerTemplate: 'sendgrid:news',
+ subject: 'Ignored',
+ data: { subject: 'From data' },
+ });
+ json = sends('api.sendgrid.com')[1].json;
+ assert.equal(json.personalizations[0].dynamic_template_data.subject, 'From data');
+
+ await router.send({ to: 'a@example.test', providerTemplate: 'sendgrid:news', data: {} });
+ json = sends('api.sendgrid.com')[2].json;
+ assert.deepEqual(json.personalizations[0].dynamic_template_data, {});
+});
+
+// ─── Startup check ─────────────────────────────────────────────────────────
+
+test('startup check: syncs a stale list, warns with key and code, stores the result', async () => {
+ reset();
+ state.sendgrid.us = [sgTemplate('d-reset', 'Reset password')];
+ state.mailgun.us.domains['mg.example.test'] = [mgTemplate('admin-reset')];
+ const warnings = [];
+ const log = { ...quietLog, warn: (message) => warnings.push(String(message)) };
+ const h = createStrapi({ accounts: [sendgridAccount('sg1'), mailgunAccount('mg1')], log });
+ const service = h.service('provider-templates');
+ await service.sync({ force: true });
+ await service.setCoreDesign(
+ 'reset-password',
+ { providerTemplate: 'sendgrid:reset-password' },
+ { id: 1 }
+ );
+ await service.setCoreDesign(
+ 'admin-forgot-password',
+ { providerTemplate: 'mailgun:admin-reset' },
+ SUPER_ADMIN
+ );
+ // A key that was never synced (for example typed into a restored database).
+ await service.updateState((current) => ({
+ ...current,
+ coreMails: {
+ ...current.coreMails,
+ 'email-confirmation': { providerTemplate: 'sendgrid:never-synced' },
+ },
+ }));
+
+ // The Mailgun template is deleted at the provider; the last sync is stale.
+ state.mailgun.us.domains['mg.example.test'] = [];
+ await service.updateState((current) => ({
+ ...current,
+ lastSyncedAt: new Date(Date.now() - 60 * 60 * 1000).toISOString(),
+ }));
+ const syncRequestsBefore = state.requests.filter((r) => r.method === 'GET').length;
+
+ await bootstrap.checkCoreDesignsAtStart(h.strapi, log);
+
+ assert.ok(
+ state.requests.filter((r) => r.method === 'GET').length > syncRequestsBefore,
+ 'the stale list was synced'
+ );
+ const problems = warnings.filter((message) => message.includes('Core email'));
+ assert.equal(problems.length, 2);
+ assert.ok(
+ problems.some(
+ (m) =>
+ m.includes('admin-forgot-password') &&
+ m.includes('mailgun:admin-reset') &&
+ m.includes('MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE')
+ )
+ );
+ assert.ok(
+ problems.some(
+ (m) =>
+ m.includes('email-confirmation') &&
+ m.includes('sendgrid:never-synced') &&
+ m.includes('MAGIC_MAIL_PROVIDER_TEMPLATE_UNKNOWN')
+ )
+ );
+ const designs = await service.coreDesigns(SUPER_ADMIN);
+ assert.equal(designs['reset-password'].usable, true);
+ assert.equal(designs['reset-password'].problem, null);
+ assert.equal(
+ designs['admin-forgot-password'].problem,
+ 'MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE'
+ );
+ assert.equal(designs['email-confirmation'].problem, 'MAGIC_MAIL_PROVIDER_TEMPLATE_UNKNOWN');
+ assert.ok(Date.parse(designs['admin-forgot-password'].checkedAt) > 0);
+ assert.equal(designs['admin-forgot-password'].editable, true);
+ const stored = (await service.getState()).coreCheck;
+ assert.equal(stored.problems.length, 2);
+
+ // A fresh list is not synced again.
+ const before = state.requests.length;
+ const fresh = await service.checkCoreDesigns({ syncIfStale: true });
+ assert.equal(fresh.synced, false);
+ assert.equal(state.requests.length, before);
+});
+
+test('startup check without provider-template core emails does nothing', async () => {
+ reset();
+ const h = createStrapi({ accounts: [sendgridAccount('sg1')] });
+ const result = await h.service('provider-templates').checkCoreDesigns();
+ assert.deepEqual(result, { checkedAt: null, synced: false, syncError: null, problems: [] });
+ assert.equal(state.requests.length, 0);
+});
+
+test('a Mailgun template without Subject header is reported as unusable for core emails', async () => {
+ reset();
+ const noSubject = mgTemplate('plain');
+ noSubject.version.headers = {};
+ state.mailgun.us.domains['mg.example.test'] = [noSubject];
+ const warnings = [];
+ const log = { ...quietLog, warn: (message) => warnings.push(String(message)) };
+ const { h, up, email, service } = await setup({ accounts: [mailgunAccount('mg1')], log });
+ try {
+ await service.setCoreDesign('reset-password', { providerTemplate: 'mailgun:plain' }, { id: 1 });
+ const designs = await service.coreDesigns();
+ assert.equal(designs['reset-password'].usable, false);
+ assert.equal(designs['reset-password'].problem, 'MAGIC_MAIL_PROVIDER_TEMPLATE_NO_SUBJECT');
+ const result = await service.checkCoreDesigns({ syncIfStale: false });
+ assert.deepEqual(result.problems, [
+ {
+ coreEmailType: 'reset-password',
+ key: 'mailgun:plain',
+ code: 'MAGIC_MAIL_PROVIDER_TEMPLATE_NO_SUBJECT',
+ },
+ ]);
+ assert.ok(warnings.some((m) => m.includes('MAGIC_MAIL_PROVIDER_TEMPLATE_NO_SUBJECT')));
+ // The send fails before anything reaches Mailgun (strict default).
+ await assert.rejects(
+ sendReset(up, email),
+ (error) => error.code === 'MAGIC_MAIL_PROVIDER_TEMPLATE_NO_SUBJECT'
+ );
+ assert.equal(sends('api.mailgun.net').length, 0);
+ } finally {
+ uninstallEmailInterception(h.strapi);
+ }
+});
diff --git a/tests/core-mails-units.test.js b/tests/core-mails-units.test.js
new file mode 100644
index 0000000..cb57dc3
--- /dev/null
+++ b/tests/core-mails-units.test.js
@@ -0,0 +1,236 @@
+'use strict';
+
+// Units for the core-mail additions of Strapi RFC #27752: the
+// admin-forgot-password payload v1, meta.strapiVersion, the admin
+// sendTemplatedEmail recognition, sample data for every core type and the
+// provider-template event payload. Synthetic data only.
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const {
+ CORE_EMAIL_TYPES,
+ buildCoreMailPayload,
+ coreMailVariableNames,
+} = require('../server/src/utils/core-mail-payload');
+const { adminForgotPasswordMail } = require('../server/src/bootstrap');
+const { emitProviderTemplateEvent } = require('../server/src/utils/provider-template-events');
+const { createStrapi } = require('./helpers/provider-template-strapi');
+
+const ADMIN_URL = 'https://cms.example.test/admin';
+const TEMPLATE = { subject: 's', text: 't' };
+const strapiWith = (config) => ({
+ config: { get: (key) => config[key] },
+});
+
+test('core email types include the admin forgot-password mail', () => {
+ assert.deepEqual(CORE_EMAIL_TYPES, [
+ 'reset-password',
+ 'email-confirmation',
+ 'admin-forgot-password',
+ ]);
+});
+
+test('admin forgot-password payload v1: user allowlist, built url, token, URLs, meta', () => {
+ const payload = buildCoreMailPayload(
+ 'admin-forgot-password',
+ {
+ url: `${ADMIN_URL}/auth/reset-password?code=abc123`,
+ user: {
+ id: 4,
+ email: 'a@example.test',
+ firstname: 'Ada',
+ lastname: 'Lovelace',
+ username: 'ada',
+ password: 'never',
+ resetPasswordToken: 'never',
+ },
+ adminUrl: ADMIN_URL,
+ serverUrl: 'https://cms.example.test',
+ },
+ { templateKey: 'sendgrid:admin-reset', locale: 'fr', strapiVersion: '5.63.0' }
+ );
+ assert.deepEqual(payload, {
+ user: {
+ id: 4,
+ email: 'a@example.test',
+ username: 'ada',
+ firstname: 'Ada',
+ lastname: 'Lovelace',
+ },
+ url: `${ADMIN_URL}/auth/reset-password?code=abc123`,
+ token: 'abc123',
+ adminUrl: ADMIN_URL,
+ serverUrl: 'https://cms.example.test',
+ meta: {
+ templateKey: 'sendgrid:admin-reset',
+ payloadVersion: 1,
+ coreEmailType: 'admin-forgot-password',
+ locale: 'fr',
+ strapiVersion: '5.63.0',
+ },
+ });
+});
+
+test('admin forgot-password: a relative or invalid link gives url "" and no token', () => {
+ for (const url of ['/admin/auth/reset-password?code=x', 'javascript:alert(1)', '', null]) {
+ const payload = buildCoreMailPayload('admin-forgot-password', { url, user: {} }, {});
+ assert.equal(payload.url, '');
+ assert.equal(payload.token, '');
+ }
+});
+
+test('meta.strapiVersion is additive: omitted when unknown, existing keys unchanged', () => {
+ const captured = {
+ URL: 'https://app.example.test/reset',
+ USER: { id: 1, email: 'u@example.test' },
+ TOKEN: 't',
+ };
+ const without = buildCoreMailPayload('reset-password', captured, { templateKey: 'k' });
+ assert.deepEqual(Object.keys(without.meta), ['templateKey', 'payloadVersion', 'coreEmailType']);
+ const withVersion = buildCoreMailPayload('reset-password', captured, {
+ templateKey: 'k',
+ strapiVersion: '5.63.0',
+ });
+ assert.equal(withVersion.meta.strapiVersion, '5.63.0');
+ const { meta: a, ...restA } = without;
+ const { meta: b, ...restB } = withVersion;
+ assert.deepEqual(restA, restB);
+ assert.equal(a.payloadVersion, b.payloadVersion);
+});
+
+test('variable names for the admin mail list the v1 keys only', () => {
+ const names = coreMailVariableNames('admin-forgot-password');
+ for (const name of ['user', 'user.email', 'url', 'token', 'adminUrl', 'serverUrl', 'meta']) {
+ assert.ok(names.includes(name), name);
+ }
+ assert.ok(names.includes('meta.strapiVersion'));
+ assert.equal(names.includes('TOKEN'), false);
+ assert.ok(coreMailVariableNames('reset-password').includes('meta.strapiVersion'));
+});
+
+test('admin sendTemplatedEmail call is recognised by template identity or reset link', () => {
+ const strapi = strapiWith({
+ 'admin.absoluteUrl': ADMIN_URL,
+ 'server.absoluteUrl': 'https://cms.example.test',
+ 'admin.forgotPassword.emailTemplate': TEMPLATE,
+ });
+ const data = { url: `${ADMIN_URL}/auth/reset-password?code=x`, user: { email: 'a@x.test' } };
+ const options = { to: 'a@x.test' };
+
+ assert.deepEqual(adminForgotPasswordMail(strapi, [options, TEMPLATE, data]), {
+ url: data.url,
+ user: data.user,
+ adminUrl: ADMIN_URL,
+ serverUrl: 'https://cms.example.test',
+ });
+ // A custom template object configured elsewhere: the reset link decides.
+ assert.ok(adminForgotPasswordMail(strapi, [options, { subject: 'x', text: 'y' }, data]));
+ // Same template, but the host overrode admin.url between calls: identity decides.
+ assert.ok(
+ adminForgotPasswordMail(strapi, [
+ options,
+ TEMPLATE,
+ { url: 'https://other.example.test/x?code=1', user: {} },
+ ])
+ );
+});
+
+test('other sendTemplatedEmail calls are not treated as the admin mail', () => {
+ const strapi = strapiWith({
+ 'admin.absoluteUrl': ADMIN_URL,
+ 'admin.forgotPassword.emailTemplate': TEMPLATE,
+ });
+ const other = { subject: 'Welcome', text: 'Hi' };
+ const cases = [
+ [{ to: 'a@x.test' }, other, { url: 'https://app.example.test/welcome', user: {} }],
+ [{ to: 'a@x.test' }, other, { url: `${ADMIN_URL}/auth/login`, user: {} }],
+ [
+ { to: 'a@x.test' },
+ TEMPLATE,
+ { url: `${ADMIN_URL}/auth/reset-password?code=x`, user: {}, extra: 1 },
+ ],
+ [{ to: 'a@x.test' }, TEMPLATE, { url: `${ADMIN_URL}/auth/reset-password?code=x` }],
+ [{ to: 'a@x.test' }, TEMPLATE, { url: 42, user: {} }],
+ [{ to: 'a@x.test' }, TEMPLATE, null],
+ [null, TEMPLATE, { url: `${ADMIN_URL}/auth/reset-password?code=x`, user: {} }],
+ ];
+ for (const args of cases) assert.equal(adminForgotPasswordMail(strapi, args), null);
+});
+
+test('test-send sample data covers every core mail that uses the template', () => {
+ const h = createStrapi();
+ const service = h.service('provider-templates');
+ const sample = service.sampleData(
+ { key: 'sendgrid:shared', usedByCoreMails: ['reset-password', 'admin-forgot-password'] },
+ 'me@example.test'
+ );
+ assert.equal(sample.TOKEN, 'sample-token', 'reset-password variables');
+ assert.equal(sample.adminUrl, 'https://api.example.test/admin');
+ assert.equal(sample.user.email, 'me@example.test');
+ assert.equal(
+ sample.meta.coreEmailType,
+ 'reset-password',
+ 'the first core mail wins shared names'
+ );
+ assert.equal(sample.name, 'Test User');
+
+ const confirmAndAdmin = service.sampleData(
+ { key: 'sendgrid:shared', usedByCoreMails: ['email-confirmation', 'admin-forgot-password'] },
+ 'me@example.test'
+ );
+ assert.equal(confirmAndAdmin.CODE, 'sample-code');
+ assert.equal(confirmAndAdmin.token, 'sample-token', 'admin token present as well');
+ assert.match(confirmAndAdmin.url, /confirmation=sample-code/);
+
+ const plain = service.sampleData({ key: 'sendgrid:x', usedByCoreMails: [] }, 'me@example.test');
+ assert.deepEqual(plain, { name: 'Test User', email: 'me@example.test' });
+});
+
+test('provider-template events carry key, code and labels only', async () => {
+ const events = [];
+ const strapi = { eventHub: { emit: async (name, payload) => events.push({ name, payload }) } };
+ await emitProviderTemplateEvent(strapi, 'failed', {
+ key: 'mailgun:x',
+ code: 'HTTP_404',
+ coreEmailType: null,
+ to: 'leak@example.test',
+ data: { token: 'leak' },
+ });
+ assert.deepEqual(events, [
+ {
+ name: 'magic-mail.provider-template.failed',
+ payload: { key: 'mailgun:x', code: 'HTTP_404', coreEmailType: null },
+ },
+ ]);
+
+ const warnings = [];
+ await emitProviderTemplateEvent(
+ {
+ log: { warn: (message) => warnings.push(message) },
+ eventHub: {
+ emit: async () => {
+ throw new Error('listener');
+ },
+ },
+ },
+ 'fallback',
+ { key: 'k', code: null }
+ );
+ assert.equal(warnings.length, 1, 'a failing listener is logged, never thrown');
+ await emitProviderTemplateEvent({}, 'failed', { key: 'k', code: null });
+});
+
+test('the admin forgot-password design is editable by super admins only', async () => {
+ const h = createStrapi();
+ const service = h.service('provider-templates');
+ const editor = { id: 2, roles: [{ code: 'strapi-editor' }] };
+ const designs = await service.coreDesigns(editor);
+ assert.equal(designs['admin-forgot-password'].editable, false);
+ assert.equal(designs['reset-password'].editable, true);
+ assert.equal(designs['admin-forgot-password'].mode, 'designer');
+ assert.equal((await service.coreDesigns())['reset-password'].editable, undefined);
+ await assert.rejects(
+ service.setCoreDesign('admin-forgot-password', { providerTemplate: null }, editor),
+ (error) => error.name === 'ForbiddenError'
+ );
+});
diff --git a/tests/helpers/provider-template-strapi.js b/tests/helpers/provider-template-strapi.js
index 21cb50e..d6aaca3 100644
--- a/tests/helpers/provider-template-strapi.js
+++ b/tests/helpers/provider-template-strapi.js
@@ -39,7 +39,9 @@ function matches(row, filters = {}) {
}
/**
- * @param {{accounts?: object[], localTemplates?: object[], log?: object, upTemplate?: Function}} [options]
+ * @param {{accounts?: object[], localTemplates?: object[], log?: object, emailPlugin?: object,
+ * usersPermissions?: object, config?: Record, db?: object}} [options]
+ * `config` answers strapi.config.get(key); `db` becomes strapi.db
* @returns {{strapi: object, tables: object, logs: object[], store: Map, service: Function}}
*/
function createStrapi({
@@ -48,6 +50,8 @@ function createStrapi({
log = quietLog,
emailPlugin = null,
usersPermissions = null,
+ config = {},
+ db = null,
} = {}) {
let counter = 0;
const nextId = () => `doc${(counter += 1)}`;
@@ -67,7 +71,10 @@ function createStrapi({
const strapi = {
log,
magicMail: {},
- config: { get: (key, fallback) => fallback },
+ config: {
+ get: (key, fallback) => (Object.hasOwn(config, key) ? config[key] : fallback),
+ },
+ ...(db ? { db } : {}),
eventHub: { emit: (name, payload) => events.push({ name, payload }) },
store: async ({ type, name }) => ({
get: async ({ key }) => {
diff --git a/tests/live/core-mails.live.test.js b/tests/live/core-mails.live.test.js
new file mode 100644
index 0000000..3217873
--- /dev/null
+++ b/tests/live/core-mails.live.test.js
@@ -0,0 +1,382 @@
+'use strict';
+
+// Opt-in live suite for the core emails (Strapi RFC #27752) against the REAL
+// SendGrid and Mailgun APIs: email confirmation, password reset and the admin
+// password reset routed through provider templates, the SendGrid subject
+// injection and the startup check.
+//
+// Run: npm run test:live (with the other live suites)
+// LIVE_PROVIDERS=sendgrid,mailgun node --test tests/live/core-mails.live.test.js
+// Needs the same ~/.config/magic-mail-live/.env as provider-templates.live.test.js
+// (SENDGRID_API_KEY, SENDGRID_FROM, SENDGRID_TEMPLATE_ID, MAILGUN_API_KEY,
+// MAILGUN_DOMAIN, MAILGUN_REGION, MAILGUN_TEMPLATE, LIVE_TEST_RECIPIENT). The
+// SendGrid key needs Template Engine write access and the Mailgun key template
+// write access: this suite creates two synthetic templates
+// (`magic-mail-live-core-`) and deletes them again in `after`.
+//
+// Nothing is delivered: SendGrid sends run in sandbox mode and Mailgun sends
+// with o:testmode=yes (forced by installLiveFetch). Values are never printed.
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const crypto = require('node:crypto');
+const { PROVIDERS, installLiveFetch, loadLiveConfig } = require('../helpers/live-env');
+
+const { env, skipReason } = loadLiveConfig({
+ sendgrid: ['SENDGRID_API_KEY', 'SENDGRID_FROM', 'SENDGRID_TEMPLATE_ID', 'LIVE_TEST_RECIPIENT'],
+ mailgun: [
+ 'MAILGUN_API_KEY',
+ 'MAILGUN_DOMAIN',
+ 'MAILGUN_REGION',
+ 'MAILGUN_TEMPLATE',
+ 'LIVE_TEST_RECIPIENT',
+ ],
+});
+
+const ready = PROVIDERS.filter((provider) => !skipReason(provider));
+for (const provider of PROVIDERS) {
+ const reason = skipReason(provider);
+ if (reason) console.log(`live core-mail suite: ${provider} tests skipped: ${reason}`);
+}
+const liveFor = (provider) => (name, fn) => test(name, { skip: skipReason(provider) || false }, fn);
+const liveSendGrid = liveFor('sendgrid');
+const liveMailgun = liveFor('mailgun');
+
+const SUBJECT = 'Magic Mail live test (can be deleted)';
+const SYNTHETIC = `magic-mail-live-core-${crypto.randomBytes(4).toString('hex')}`;
+const ADMIN_URL = 'https://cms.example.test/admin';
+const SERVER_URL = 'https://cms.example.test';
+const ADMIN_TEMPLATE = Object.freeze({ subject: 'Reset password', text: 'Reset: <%= url %>' });
+const SUPER_ADMIN = { id: 1, roles: [{ code: 'strapi-super-admin' }] };
+
+const sgHost = () => (env.SENDGRID_REGION === 'eu' ? 'api.eu.sendgrid.com' : 'api.sendgrid.com');
+const mgHost = () => (env.MAILGUN_REGION === 'eu' ? 'api.eu.mailgun.net' : 'api.mailgun.net');
+const sgAuth = () => ({ Authorization: `Bearer ${env.SENDGRID_API_KEY}` });
+const mgAuth = () => ({
+ Authorization: `Basic ${Buffer.from(`api:${env.MAILGUN_API_KEY}`).toString('base64')}`,
+});
+
+let live;
+let previousKey;
+const created = { sendgridId: null, mailgunName: null };
+const cleanup = { sendgrid: null, mailgun: null };
+
+/** Creates the synthetic SendGrid dynamic template whose subject is {{subject}}. */
+async function createSendGridTemplate() {
+ const response = await fetch(`https://${sgHost()}/v3/templates`, {
+ method: 'POST',
+ headers: { ...sgAuth(), 'content-type': 'application/json' },
+ body: JSON.stringify({ name: SYNTHETIC, generation: 'dynamic' }),
+ });
+ assert.equal(response.status, 201, 'SendGrid template created (Template Engine write access)');
+ const { id } = await response.json();
+ created.sendgridId = id;
+ const version = await fetch(`https://${sgHost()}/v3/templates/${id}/versions`, {
+ method: 'POST',
+ headers: { ...sgAuth(), 'content-type': 'application/json' },
+ body: JSON.stringify({
+ template_id: id,
+ active: 1,
+ name: 'v1',
+ subject: '{{subject}}',
+ html_content: '{{name}} {{url}}
',
+ plain_content: '{{name}} {{url}}',
+ }),
+ });
+ assert.equal(version.status, 201, 'SendGrid template version created');
+}
+
+/** Creates the synthetic Mailgun domain template with a Subject header. */
+async function createMailgunTemplate() {
+ const form = new FormData();
+ form.set('name', SYNTHETIC);
+ form.set('description', SUBJECT);
+ form.set('template', '{{url}} {{user.email}} {{meta.coreEmailType}}
');
+ form.set('engine', 'handlebars');
+ form.set('tag', 'v1');
+ form.set('headers', JSON.stringify({ Subject: SUBJECT }));
+ const response = await fetch(
+ `https://${mgHost()}/v3/${encodeURIComponent(env.MAILGUN_DOMAIN)}/templates`,
+ { method: 'POST', headers: mgAuth(), body: form }
+ );
+ assert.equal(response.status, 200, 'Mailgun template created (template write access)');
+ created.mailgunName = SYNTHETIC;
+}
+
+test.before(async () => {
+ if (ready.length === 0) return;
+ previousKey = process.env.MAGIC_MAIL_ENCRYPTION_KEY;
+ process.env.MAGIC_MAIL_ENCRYPTION_KEY = crypto.randomBytes(32).toString('hex');
+ live = installLiveFetch();
+ if (ready.includes('sendgrid')) await createSendGridTemplate();
+ if (ready.includes('mailgun')) await createMailgunTemplate();
+});
+
+test.after(async () => {
+ if (ready.length === 0) return;
+ // Restore the accounts: delete both synthetic templates and confirm.
+ if (created.sendgridId) {
+ const response = await fetch(`https://${sgHost()}/v3/templates/${created.sendgridId}`, {
+ method: 'DELETE',
+ headers: sgAuth(),
+ });
+ const check = await fetch(`https://${sgHost()}/v3/templates/${created.sendgridId}`, {
+ headers: sgAuth(),
+ });
+ cleanup.sendgrid = { deleteStatus: response.status, afterStatus: check.status };
+ }
+ if (created.mailgunName) {
+ const path = `/v3/${encodeURIComponent(env.MAILGUN_DOMAIN)}/templates/${created.mailgunName}`;
+ const response = await fetch(`https://${mgHost()}${path}`, {
+ method: 'DELETE',
+ headers: mgAuth(),
+ });
+ const check = await fetch(`https://${mgHost()}${path}`, { headers: mgAuth() });
+ cleanup.mailgun = { deleteStatus: response.status, afterStatus: check.status };
+ }
+ live.restore();
+ if (previousKey === undefined) delete process.env.MAGIC_MAIL_ENCRYPTION_KEY;
+ else process.env.MAGIC_MAIL_ENCRYPTION_KEY = previousKey;
+ console.log(JSON.stringify({ cleanup, liveRequests: live.results }, null, 1));
+ if (cleanup.sendgrid) assert.equal(cleanup.sendgrid.afterStatus, 404, 'SendGrid cleanup');
+ if (cleanup.mailgun) assert.equal(cleanup.mailgun.afterStatus, 404, 'Mailgun cleanup');
+});
+
+const interpolate = (layout, data) =>
+ layout.replace(/<%=\s*([\w.]+)\s*%>/g, (_, path) =>
+ String(path.split('.').reduce((value, part) => value?.[part], data) ?? '')
+ );
+
+let h;
+let email;
+let up;
+/** Strapi harness with interception, one live account per ready provider. */
+function harness() {
+ if (h) return h;
+ const { createStrapi, quietLog } = require('../helpers/provider-template-strapi');
+ const { encryptCredentials } = require('../../server/src/utils/encryption');
+ const { installEmailInterception } = require('../../server/src/bootstrap');
+ const accounts = [];
+ if (ready.includes('sendgrid')) {
+ accounts.push({
+ documentId: 'live-sendgrid',
+ name: 'live-sendgrid',
+ provider: 'sendgrid',
+ fromEmail: env.SENDGRID_FROM,
+ isActive: true,
+ priority: 5,
+ config: encryptCredentials({
+ apiKey: env.SENDGRID_API_KEY,
+ region: env.SENDGRID_REGION === 'eu' ? 'eu' : 'us',
+ }),
+ });
+ }
+ if (ready.includes('mailgun')) {
+ accounts.push({
+ documentId: 'live-mailgun',
+ name: 'live-mailgun',
+ provider: 'mailgun',
+ fromEmail: env.MAILGUN_FROM || `magic-mail-live@${env.MAILGUN_DOMAIN}`,
+ isActive: true,
+ priority: 4,
+ config: encryptCredentials({
+ apiKey: env.MAILGUN_API_KEY,
+ domain: env.MAILGUN_DOMAIN,
+ region: env.MAILGUN_REGION === 'eu' ? 'eu' : 'us',
+ }),
+ });
+ }
+ const nativeSends = [];
+ const provider = {
+ send: async (options) => {
+ nativeSends.push(options);
+ return { messageId: 'native' };
+ },
+ };
+ const service = {
+ send: (options) => provider.send(options),
+ sendTemplatedEmail: (options, template, data) =>
+ provider.send({
+ ...options,
+ subject: interpolate(template.subject, data),
+ text: interpolate(template.text, data),
+ }),
+ };
+ email = { service, nativeSends };
+ const upService = { template: (layout, data) => interpolate(layout, data) };
+ up = upService;
+ h = createStrapi({
+ accounts,
+ emailPlugin: { provider, service: () => service },
+ usersPermissions: { service: (name) => (name === 'users-permissions' ? upService : null) },
+ config: {
+ 'admin.absoluteUrl': ADMIN_URL,
+ 'server.absoluteUrl': SERVER_URL,
+ 'admin.forgotPassword.emailTemplate': ADMIN_TEMPLATE,
+ 'info.strapi': '5.63.0',
+ },
+ db: { query: () => ({ findOne: async () => ({ id: 1, preferedLanguage: 'en' }) }) },
+ });
+ installEmailInterception(h.strapi, quietLog);
+ return h;
+}
+
+let syncPromise;
+const syncOnce = () => {
+ syncPromise ??= harness().service('provider-templates').sync({ force: true });
+ return syncPromise;
+};
+const rowKey = (predicate) =>
+ harness().tables['plugin::magic-mail.provider-template'].find(predicate)?.key;
+
+/** users-permissions sendConfirmationEmail(), live recipient, synthetic user. */
+function confirmEmail() {
+ const data = {
+ URL: `${SERVER_URL}/api/auth/email-confirmation`,
+ SERVER_URL,
+ ADMIN_URL,
+ USER: { id: 9, email: env.LIVE_TEST_RECIPIENT, username: 'live.user' },
+ CODE: crypto.randomBytes(8).toString('hex'),
+ };
+ const body = up.template('<%= URL %>?confirmation=<%= CODE %>
', data);
+ return email.service.send({
+ to: env.LIVE_TEST_RECIPIENT,
+ subject: 'Account confirmation',
+ text: body,
+ html: body,
+ });
+}
+
+/** users-permissions forgotPassword(). */
+function resetPassword() {
+ const data = {
+ URL: 'https://app.example.test/reset',
+ SERVER_URL,
+ ADMIN_URL,
+ USER: { id: 9, email: env.LIVE_TEST_RECIPIENT, username: 'live.user' },
+ TOKEN: crypto.randomBytes(8).toString('hex'),
+ };
+ const body = up.template('<%= URL %>?code=<%= TOKEN %>
', data);
+ return email.service.send({
+ to: env.LIVE_TEST_RECIPIENT,
+ subject: 'Reset password',
+ text: body,
+ html: body,
+ });
+}
+
+/** @strapi/admin forgotPassword(). */
+function adminForgotPassword() {
+ return email.service.sendTemplatedEmail(
+ { to: env.LIVE_TEST_RECIPIENT, from: undefined, replyTo: undefined },
+ ADMIN_TEMPLATE,
+ {
+ url: `${ADMIN_URL}/auth/reset-password?code=${crypto.randomBytes(8).toString('hex')}`,
+ user: { email: env.LIVE_TEST_RECIPIENT, firstname: 'Live', lastname: 'Test' },
+ }
+ );
+}
+
+const CORE_SENDS = [
+ ['email-confirmation', confirmEmail],
+ ['reset-password', resetPassword],
+ ['admin-forgot-password', adminForgotPassword],
+];
+
+// ── SendGrid ──────────────────────────────────────────────────────────────
+
+liveSendGrid('SendGrid: core emails go through the real dynamic template (sandbox)', async () => {
+ await syncOnce();
+ const key = rowKey((r) => r.provider === 'sendgrid' && r.remoteId === env.SENDGRID_TEMPLATE_ID);
+ assert.ok(key, 'SENDGRID_TEMPLATE_ID synced');
+ const service = harness().service('provider-templates');
+ for (const [type, send] of CORE_SENDS) {
+ await service.setCoreDesign(type, { providerTemplate: key }, SUPER_ADMIN);
+ const result = await send();
+ assert.equal(result.success, true, `${type} accepted by SendGrid`);
+ const body = live.sent.sendgrid.at(-1);
+ assert.equal(body.template_id, env.SENDGRID_TEMPLATE_ID);
+ assert.equal(body.mail_settings.sandbox_mode.enable, true);
+ const data = body.personalizations[0].dynamic_template_data;
+ assert.equal(data.meta.coreEmailType, type);
+ assert.equal(data.meta.payloadVersion, 1);
+ assert.equal(data.meta.strapiVersion, '5.63.0');
+ assert.match(data.url, /^https:\/\//);
+ assert.equal(body.content, undefined, `${type}: no designer body`);
+ await service.setCoreDesign(type, { providerTemplate: null }, SUPER_ADMIN);
+ }
+ assert.equal(email.nativeSends.length, 0);
+});
+
+liveSendGrid('SendGrid: a passed subject reaches a {{subject}} template (sandbox)', async () => {
+ await syncOnce();
+ const key = rowKey((r) => r.provider === 'sendgrid' && r.remoteId === created.sendgridId);
+ assert.ok(key, 'synthetic SendGrid template synced');
+ const detail = await harness().service('provider-templates').detail(key);
+ assert.ok(
+ detail.variables.some((v) => v.path === 'subject'),
+ 'variable detection finds {{subject}} in the real template'
+ );
+ const result = await harness()
+ .service('email-router')
+ .send({
+ to: env.LIVE_TEST_RECIPIENT,
+ providerTemplate: key,
+ subject: SUBJECT,
+ data: { name: 'Live Test', url: 'https://example.test' },
+ });
+ assert.equal(result.success, true);
+ const body = live.sent.sendgrid.at(-1);
+ assert.equal(body.template_id, created.sendgridId);
+ assert.equal(body.personalizations[0].dynamic_template_data.subject, SUBJECT);
+});
+
+// ── Mailgun ───────────────────────────────────────────────────────────────
+
+liveMailgun(
+ 'Mailgun: core emails go through a real template with Subject header (test mode)',
+ async () => {
+ await syncOnce();
+ const key = rowKey((r) => r.provider === 'mailgun' && r.name === created.mailgunName);
+ assert.ok(key, 'synthetic Mailgun template synced');
+ const service = harness().service('provider-templates');
+ assert.equal(
+ (await service.overview()).templates.find((t) => t.key === key).subject,
+ SUBJECT,
+ 'the Subject header was synced'
+ );
+ for (const [type, send] of CORE_SENDS) {
+ await service.setCoreDesign(type, { providerTemplate: key }, SUPER_ADMIN);
+ const result = await send();
+ assert.equal(result.success, true, `${type} accepted by Mailgun`);
+ const form = Object.fromEntries(live.sent.mailgun.at(-1));
+ assert.equal(form.template, created.mailgunName);
+ assert.equal(form['o:testmode'], 'yes');
+ assert.equal(form.subject, undefined, 'the template Subject header is used');
+ const vars = JSON.parse(form['t:variables']);
+ assert.equal(vars.meta.coreEmailType, type);
+ assert.match(vars.url, /^https:\/\//);
+ await service.setCoreDesign(type, { providerTemplate: null }, SUPER_ADMIN);
+ }
+ assert.equal(email.nativeSends.length, 0);
+ }
+);
+
+liveMailgun('Mailgun: the startup check flags a real template without Subject header', async () => {
+ await syncOnce();
+ const service = harness().service('provider-templates');
+ const plain = rowKey((r) => r.provider === 'mailgun' && r.name === env.MAILGUN_TEMPLATE);
+ const synthetic = rowKey((r) => r.provider === 'mailgun' && r.name === created.mailgunName);
+ const plainRow = (await service.overview()).templates.find((t) => t.key === plain);
+ await service.setCoreDesign('reset-password', { providerTemplate: synthetic }, SUPER_ADMIN);
+ await service.setCoreDesign('admin-forgot-password', { providerTemplate: plain }, SUPER_ADMIN);
+ const result = await service.checkCoreDesigns({ syncIfStale: false });
+ const flagged = result.problems.map((p) => `${p.coreEmailType}:${p.code}`);
+ if (plainRow.subject) {
+ assert.deepEqual(flagged, [], 'MAILGUN_TEMPLATE has a Subject header: nothing to flag');
+ } else {
+ assert.deepEqual(flagged, ['admin-forgot-password:MAGIC_MAIL_PROVIDER_TEMPLATE_NO_SUBJECT']);
+ }
+ await service.setCoreDesign('reset-password', { providerTemplate: null }, SUPER_ADMIN);
+ await service.setCoreDesign('admin-forgot-password', { providerTemplate: null }, SUPER_ADMIN);
+});