fix: properly awaits email send to catch potential errors #2444 (#2470)

This commit is contained in:
Jacob Fletcher
2023-04-10 13:50:27 -04:00
committed by GitHub
parent 299ae4fce5
commit 11a6ce6d3a
2 changed files with 26 additions and 1 deletions

View File

@@ -2,9 +2,10 @@ import { SendMailOptions } from 'nodemailer';
export default async function sendEmail(message: SendMailOptions): Promise<unknown> {
let result;
try {
const email = await this.email;
result = email.transport.sendMail(message);
result = await email.transport.sendMail(message);
} catch (err) {
this.logger.error(
`Failed to send mail to ${message.to}, subject: ${message.subject}`,
@@ -12,5 +13,6 @@ export default async function sendEmail(message: SendMailOptions): Promise<unkno
);
return err;
}
return result;
}

View File

@@ -35,6 +35,29 @@ export const customIdNumberSlug = 'custom-id-number';
export const errorOnHookSlug = 'error-on-hooks';
export default buildConfig({
endpoints: [
{
path: '/send-test-email',
method: 'get',
handler: async (req, res) => {
await req.payload.sendEmail({
from: 'dev@payloadcms.com',
to: devUser.email,
subject: 'Test Email',
html: 'This is a test email.',
// to recreate a failing email transport, add the following credentials
// to the `email` property of `payload.init()` in `../dev.ts`
// the app should fail to send the email, but the error should be handled without crashing the app
// transportOptions: {
// host: 'smtp.ethereal.email',
// port: 587,
// },
});
res.status(200).send('Email sent');
},
},
],
collections: [
{
slug,