Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
## [Unreleased]

### Fixed

* **Recipient names with commas, quotes or angle brackets arrive unchanged.** `"Doe, Jane" <jane@example.com>` in to, cc or bcc used to be split at the comma and partly lower-cased, so the recipient saw the name "doe, Jane" (SMTP, Gmail, Outlook, Yahoo and Mailgun). Addresses are now read with the same RFC 5322 parser the transports use; only the address is lower-cased, never the name. Bare address lists are normalised exactly as before.

## [4.6.1](https://github.com/Schero94/Magic-Mail/compare/v4.6.0...v4.6.1) (2026-11-18)


Expand Down
76 changes: 57 additions & 19 deletions server/src/services/email-router.js
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,59 @@ function parseAddressList(value) {
return out;
}

/** RFC 5322 atext plus spaces and Unicode letters: a display name that needs no quotes. */
const PLAIN_DISPLAY_NAME = /^[\p{L}\p{M}\p{N} !#$%&'*+\-/=?^_`{|}~]+$/u;

/**
* Formats one parsed mailbox with a lower-cased address. The display name is
* kept byte for byte; it is quoted (with `"` and `\` escaped) only when it
* contains characters that would otherwise change how it parses, such as a
* comma or angle brackets.
*
* @param {{name?: string, address: string}} entry
* @returns {string}
*/
function formatNormalizedMailbox(entry) {
const address = entry.address.trim().toLowerCase();
const name = entry.name || '';
if (!name) return address;
const phrase = PLAIN_DISPLAY_NAME.test(name) ? name : `"${name.replace(/["\\]/g, '\\$&')}"`;
return `${phrase} <${address}>`;
}

/**
* Normalises one recipient string: parsed with the RFC 5322 parser the
* transports use, so commas, quotes and angle brackets inside quoted display
* names are kept. Only the address part is lower-cased (RFC 5321: the domain
* is case-insensitive; Magic Mail has always lower-cased the whole address).
* Values the parser cannot read as plain mailboxes (groups, empty addresses)
* are returned trimmed and otherwise unchanged; validation handles them later.
*
* @param {*} value
* @returns {*} the normalised string, or the value unchanged when it is not a string
*/
function normalizeRecipientString(value) {
if (typeof value !== 'string') return value;
const entries = getAddressParser()(value);
if (entries.length === 0 || entries.some((e) => Array.isArray(e.group) || !e.address)) {
return value.trim();
}
return entries.map(formatNormalizedMailbox).join(', ');
}

/**
* Normalises a to/cc/bcc value (string, array of strings, or `{ name, address }`
* objects, which are passed through) without touching display names.
*
* @param {*} value
* @returns {*}
*/
function normalizeRecipients(value) {
if (!value) return value;
if (Array.isArray(value)) return value.map(normalizeRecipientString);
return normalizeRecipientString(value);
}

/**
* Returns the bare, lower-cased addresses of a recipient value.
* @param {*} value
Expand Down Expand Up @@ -1006,25 +1059,10 @@ module.exports = ({ strapi }) => ({
throw validationError('Recipient email address (to) is required');
}

// Normalize addresses (RFC 5321: the domain part is case-insensitive).
const normalizeAddr = (addr) => {
if (typeof addr !== 'string') return addr;
if (addr.includes('<') && addr.includes('>')) {
return addr.replace(/<([^>]+)>/, (_, email) => `<${email.trim().toLowerCase()}>`);
}
return addr.trim().toLowerCase();
};
const normalizeAddrs = (value) => {
if (!value) return value;
if (Array.isArray(value)) return value.map(normalizeAddr);
if (typeof value === 'string' && value.includes(',')) {
return value.split(',').map(normalizeAddr).join(', ');
}
return normalizeAddr(value);
};
data.to = normalizeAddrs(data.to);
if (data.cc) data.cc = normalizeAddrs(data.cc);
if (data.bcc) data.bcc = normalizeAddrs(data.bcc);
// Lower-case the address parts; display names stay exactly as given.
data.to = normalizeRecipients(data.to);
if (data.cc) data.cc = normalizeRecipients(data.cc);
if (data.bcc) data.bcc = normalizeRecipients(data.bcc);

if (data.skipLinkTracking) {
strapi.log.debug('[magic-mail] [SKIP-TRACK] Link tracking disabled for this email');
Expand Down
174 changes: 174 additions & 0 deletions tests/address-display-names.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
'use strict';

// Regression tests: display names in to/cc/bcc reach every provider
// unchanged. send() used to split address strings on every comma (also
// inside quoted display names) and lower-case the pieces, so
// `"Ops, Live" <cc@x>` arrived as `"ops, Live" <cc@x>`. Found by the live
// SendGrid run (SG-9). Only the address part may be lower-cased.
// Synthetic data only; fetch is faked and the SMTP/OAuth transports are
// replaced by recorders at the provider boundary.

const test = require('node:test');
const assert = require('node:assert/strict');

const {
accountFor,
createHarness,
fakeFetch,
withEncryptionKey,
} = require('./helpers/provider-send-harness');

/** Input address strings and the mailboxes every provider must receive. */
const CASES = [
{
label: 'comma in a quoted name',
cc: '"Ops, Live" <CC@Example.test>',
expected: [{ name: 'Ops, Live', address: 'cc@example.test' }],
},
{
label: 'escaped quotes and a comma in a quoted name',
cc: '"Doe, Jane \\"JD\\"" <jd@example.test>',
expected: [{ name: 'Doe, Jane "JD"', address: 'jd@example.test' }],
},
{
label: 'unicode names, quoted with a comma and unquoted',
cc: '"Müller, Zoë" <zoe@example.test>, Zoë Müller <ZOE2@example.test>',
expected: [
{ name: 'Müller, Zoë', address: 'zoe@example.test' },
{ name: 'Zoë Müller', address: 'zoe2@example.test' },
],
},
{
label: 'angle brackets inside a quoted name',
cc: '"Ops <Team>" <OPS@example.test>',
expected: [{ name: 'Ops <Team>', address: 'ops@example.test' }],
},
{
label: 'mixed list: quoted comma name, plain name, bare address',
cc: '"Ops, Live" <a@example.test>, Bob Builder <B@Example.test>, C@example.test',
expected: [
{ name: 'Ops, Live', address: 'a@example.test' },
{ name: 'Bob Builder', address: 'b@example.test' },
{ name: '', address: 'c@example.test' },
],
},
{
label: 'array items with quoted comma names',
cc: ['"Ops, Live" <a@example.test>', '"Ünal, Ada" <ADA@example.test>'],
expected: [
{ name: 'Ops, Live', address: 'a@example.test' },
{ name: 'Ünal, Ada', address: 'ada@example.test' },
],
},
];

const TO = 'Primary Person <TO@Example.test>';
const TO_EXPECTED = [{ name: 'Primary Person', address: 'to@example.test' }];

/**
* Parses what a provider received into mailboxes.
*
* @param {*} value
* @returns {{name: string, address: string}[]}
*/
function mailboxes(value) {
const parse = require('nodemailer/lib/addressparser');
const items = Array.isArray(value) ? value : [value];
return items.flatMap((item) =>
typeof item === 'string'
? parse(item).map((e) => ({ name: e.name || '', address: (e.address || '').toLowerCase() }))
: [{ name: item.name || '', address: String(item.address).toLowerCase() }]
);
}

for (const { label, cc, expected } of CASES) {
test(`SendGrid receives the right addresses: ${label}`, async () => {
// SendGrid sends bare addresses in this release (names are not passed
// on), so only the addresses are compared.
const restoreKey = withEncryptionKey();
const fetchFake = fakeFetch();
try {
const { router } = createHarness([accountFor('sendgrid')]);
await router.send({ to: TO, cc, subject: 'Names', text: 'x' });
const p = fetchFake.calls.at(-1).json.personalizations[0];
assert.deepEqual(
p.to.map((entry) => entry.email),
TO_EXPECTED.map((m) => m.address)
);
assert.deepEqual(
p.cc.map((entry) => entry.email),
expected.map((m) => m.address)
);
} finally {
fetchFake.restore();
restoreKey();
}
});

test(`Mailgun keeps display names: ${label}`, async () => {
const restoreKey = withEncryptionKey();
const fetchFake = fakeFetch();
try {
const { router } = createHarness([accountFor('mailgun')]);
await router.send({ to: TO, cc, subject: 'Names', text: 'x' });
const form = fetchFake.calls.at(-1).form;
const field = (key) => form.filter(([k]) => k === key).map(([, v]) => v);
assert.deepEqual(mailboxes(field('to')), TO_EXPECTED);
assert.deepEqual(mailboxes(field('cc')), expected);
} finally {
fetchFake.restore();
restoreKey();
}
});

for (const [provider, method] of [
['smtp', 'sendViaSMTP'],
['gmail-oauth', 'sendViaGmailOAuth'],
['microsoft-oauth', 'sendViaMicrosoftOAuth'],
['yahoo-oauth', 'sendViaYahooOAuth'],
]) {
test(`${provider} receives the display names unchanged: ${label}`, async () => {
const restoreKey = withEncryptionKey();
try {
const account = { ...accountFor('sendgrid'), provider, documentId: `acc-${provider}` };
const { router } = createHarness([account]);
let received;
router[method] = async (_account, emailData) => {
received = emailData;
return { messageId: 'm1' };
};
await router.send({ to: TO, cc, bcc: cc, subject: 'Names', text: 'x' });
assert.deepEqual(mailboxes(received.to), TO_EXPECTED);
assert.deepEqual(mailboxes(received.cc), expected);
assert.deepEqual(mailboxes(received.bcc), expected);
} finally {
restoreKey();
}
});
}
}

test('bare address lists are normalised exactly as before', async () => {
const restoreKey = withEncryptionKey();
try {
const account = { ...accountFor('sendgrid'), provider: 'smtp', documentId: 'acc-smtp' };
const { router } = createHarness([account]);
let received;
router.sendViaSMTP = async (_account, emailData) => {
received = emailData;
return { messageId: 'm1' };
};
await router.send({
to: ['Ada@Example.test', 'bob@example.test'],
cc: 'Carol@Example.test,dave@example.test',
bcc: ' Eve@Example.test ',
subject: 'Bare',
text: 'x',
});
assert.deepEqual(received.to, ['ada@example.test', 'bob@example.test']);
assert.equal(received.cc, 'carol@example.test, dave@example.test');
assert.equal(received.bcc, 'eve@example.test');
} finally {
restoreKey();
}
});
Loading
Loading