feat: add trpc route to send emails

This commit is contained in:
Ephraim Atta-Duncan
2023-06-19 16:33:30 +00:00
parent aa740864b8
commit bc11abda08
11 changed files with 1095 additions and 4 deletions

View File

@ -0,0 +1,39 @@
import nodemailer from 'nodemailer';
import nodemailerSendgrid from 'nodemailer-sendgrid';
export const sendMail = async ({ email }: { email: string }) => {
let transporter;
if (process.env.NEXT_PRIVATE_SENDGRID_API_KEY) {
transporter = nodemailer.createTransport(
nodemailerSendgrid({
apiKey: process.env.NEXT_PRIVATE_SENDGRID_API_KEY,
}),
);
}
if (process.env.NEXT_PRIVATE_SMTP_MAIL_HOST) {
transporter = nodemailer.createTransport({
host: process.env.NEXT_PRIVATE_SMTP_MAIL_HOST,
port: Number(process.env.NEXT_PRIVATE_SMTP_MAIL_PORT),
auth: {
user: process.env.NEXT_PRIVATE_SMTP_MAIL_USER,
pass: process.env.NEXT_PRIVATE_SMTP_MAIL_PASSWORD,
},
});
}
if (!transporter) {
throw new Error(
'No mail transport configured. Probably Sendgrid API Key nor SMTP Mail host was set',
);
}
await transporter.sendMail({
from: 'Documenso <hi@documenso.com>',
to: email,
subject: 'Welcome to Documenso!',
text: 'Welcome to Documenso!',
html: '<p>Welcome to Documenso!</p>',
});
};

View File

@ -0,0 +1,26 @@
import { TRPCError } from '@trpc/server';
import { sendMail } from '@documenso/lib/server-only/document/send-document';
import { authenticatedProcedure, router } from '../trpc';
import { ZSendMailMutationSchema } from './schema';
export const documentRouter = router({
sendEmail: authenticatedProcedure
.input(ZSendMailMutationSchema)
.mutation(async ({ input, ctx }) => {
try {
const { email } = input;
console.log('Send Mail Context', ctx);
return await sendMail({ email });
} catch (err) {
console.error(err);
throw new TRPCError({
code: 'BAD_REQUEST',
message: 'We were unable to send an email.',
});
}
}),
});

View File

@ -0,0 +1,7 @@
import { z } from 'zod';
export const ZSendMailMutationSchema = z.object({
email: z.string().min(1).email(),
});
export type TSendMailMutationSchema = z.infer<typeof ZSendMailMutationSchema>;

View File

@ -1,4 +1,5 @@
import { authRouter } from './auth-router/router';
import { documentRouter } from './document-router/router';
import { profileRouter } from './profile-router/router';
import { procedure, router } from './trpc';
@ -6,6 +7,7 @@ export const appRouter = router({
hello: procedure.query(() => 'Hello, world!'),
auth: authRouter,
profile: profileRouter,
document: documentRouter,
});
export type AppRouter = typeof appRouter;