Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(email-nodemailer): add email recipient override config #10050

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
10 changes: 10 additions & 0 deletions packages/email-nodemailer/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,14 @@ import { InvalidConfiguration } from 'payload'
export type NodemailerAdapterArgs = {
defaultFromAddress: string
defaultFromName: string
/**
* Override all emails to be sent to this address.
* Useful for testing.
*/
overrideRecipientAddress?: string
/**
* Skip verifying the email SMTP transport.
*/
skipVerify?: boolean
transport?: Transporter
transportOptions?: SMTPConnection.Options
Expand All @@ -25,6 +33,7 @@ export const nodemailerAdapter = async (
args?: NodemailerAdapterArgs,
): Promise<NodemailerAdapter> => {
const { defaultFromAddress, defaultFromName, transport } = await buildEmail(args)
const overrideRecipientAddress = args?.overrideRecipientAddress

const adapter: NodemailerAdapter = () => ({
name: 'nodemailer',
Expand All @@ -34,6 +43,7 @@ export const nodemailerAdapter = async (
return await transport.sendMail({
from: `${defaultFromName} <${defaultFromAddress}>`,
...message,
...(overrideRecipientAddress ? { to: overrideRecipientAddress } : {}),
})
},
})
Expand Down
12 changes: 11 additions & 1 deletion packages/email-resend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ export type ResendAdapterArgs = {
apiKey: string
defaultFromAddress: string
defaultFromName: string
/**
* Override all emails to be sent to this address.
* Useful for testing.
*/
overrideRecipientAddress?: string
}

type ResendAdapter = EmailAdapter<ResendResponse>
Expand All @@ -29,9 +34,14 @@ export const resendAdapter = (args: ResendAdapterArgs): ResendAdapter => {
defaultFromAddress,
defaultFromName,
sendEmail: async (message) => {
const modifiedMessage = {
...message,
...(args.overrideRecipientAddress ? { to: args.overrideRecipientAddress } : {}),
}

// Map the Payload email options to Resend email options
const sendEmailOptions = mapPayloadEmailToResendEmail(
message,
modifiedMessage,
defaultFromAddress,
defaultFromName,
)
Expand Down
26 changes: 14 additions & 12 deletions test/email-nodemailer/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,22 @@ export default buildConfigWithDefaults({
collections: [],
email: nodemailerAdapter(),
onInit: async (payload) => {
await payload.create({
collection: 'users',
data: {
email: devUser.email,
password: devUser.password,
},
})
if (process.env.SKIP_ON_INIT !== 'true') {
await payload.create({
collection: 'users',
data: {
email: devUser.email,
password: devUser.password,
},
})

const email = await payload.sendEmail({
subject: 'This was sent on init',
to: '[email protected]',
})
const email = await payload.sendEmail({
subject: 'This was sent on init',
to: '[email protected]',
})

payload.logger.info({ email, msg: 'Email sent' })
payload.logger.info({ email, msg: 'Email sent' })
}
},
typescript: {
outputFile: path.resolve(dirname, 'payload-types.ts'),
Expand Down
106 changes: 106 additions & 0 deletions test/email-nodemailer/int.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import type { NodemailerAdapterArgs } from '@payloadcms/email-nodemailer'
import type { Payload } from 'payload'

import { nodemailerAdapter } from '@payloadcms/email-nodemailer'
import path from 'path'
import { fileURLToPath } from 'url'

import { initPayloadInt } from '../helpers/initPayloadInt.js'

let payload: Payload
let mockedSendEmail: jest.Mock

const overrideRecipientAddress = '[email protected]'

const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)

type EmailReturnType = {
subject: string
text: string
to: string
}

describe('@payloadcms/email-nodemailer', () => {
beforeAll(async () => {
process.env.SKIP_ON_INIT = 'true'
;({ payload } = await initPayloadInt(dirname))

mockedSendEmail = jest.fn()
})

afterAll(async () => {
if (typeof payload?.db?.destroy === 'function') {
await payload.db.destroy()
}
})

describe('without basic config', () => {
beforeEach(async () => {
// Partially mocked transport
const mockedTransport = {
// eslint-disable-next-line @typescript-eslint/require-await
sendMail: async (message) => {
mockedSendEmail()
return message
},
} as NodemailerAdapterArgs['transport']

const adapter = await nodemailerAdapter({
defaultFromAddress: '[email protected]',
defaultFromName: 'Test',
skipVerify: true,
transport: mockedTransport,
})

const mockedAdapter = adapter({ payload })

payload.email = mockedAdapter
})

it('sends email with overrideRecipientAddress', async () => {
const email = (await payload.email.sendEmail({
to: '[email protected]',
text: 'Hello, world!',
subject: 'Test email',
})) as EmailReturnType

expect(email.to).toEqual('[email protected]')
})
})

describe('with overrideRecipientAddress', () => {
beforeEach(async () => {
// Partially mocked transport
const mockedTransport = {
// eslint-disable-next-line @typescript-eslint/require-await
sendMail: async (message) => {
mockedSendEmail()
return message
},
} as NodemailerAdapterArgs['transport']

const adapter = await nodemailerAdapter({
overrideRecipientAddress,
defaultFromAddress: '[email protected]',
defaultFromName: 'Test',
skipVerify: true,
transport: mockedTransport,
})

const mockedAdapter = adapter({ payload })

payload.email = mockedAdapter
})

it('sends email with overrideRecipientAddress', async () => {
const email = (await payload.email.sendEmail({
to: '[email protected]',
text: 'Hello, world!',
subject: 'Test email',
})) as EmailReturnType

expect(email.to).toEqual(overrideRecipientAddress)
})
})
})
Loading