Skip to content

Commit

Permalink
fix: properly awaits email send to catch potential errors #2444 (#2470)
Browse files Browse the repository at this point in the history
  • Loading branch information
jacobsfletch authored Apr 10, 2023
1 parent 299ae4f commit 11a6ce6
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/email/sendEmail.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,17 @@ 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}`,
err,
);
return err;
}

return result;
}
23 changes: 23 additions & 0 deletions test/collections-rest/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit 11a6ce6

Please sign in to comment.