I using Next Js for front end, Nest Js for back end and AWS SES v2 for email service. Currently I am sending emails using EJS email templates that I made in back end. I would like to switch to React Emails. But React emails is generated at front end and use JSX, so how do I implement React Email in my project?
1 Answer
Installation & Basic Setup
React Email uses React for its syntax. You can use React Email in your backend like so:
- Create something like an emails folder in your backend.
- Install the required dependencies for it in your top level backend folder using
npm install react-email @react-email/button @react-email/html -E - Add an
email:devscript to your backendpackage.jsonlike so:
{
"scripts": {
"dev": "email dev"
}
}
- Create a demo email in your previously created
emailsfolder like so:
import { Button } from "@react-email/button";
import { Html } from "@react-email/html";
import * as React from "react";
export default function Email() {
return (
<Html>
<Button
href="https://example.com"
style={{ background: "#000", color: "#fff", padding: "12px 20px" }}
>
Click me
</Button>
</Html>
);
}
- Preview using
npm run emails:dev
Sending emails
After all this, you have to actually send the emails. Follow these steps to get started sending them:
- Create an API route called something like
/send-email - In the API route, use the following code and adjust to your needs.
import { render } from '@react-email/render';
import { SES } from '@aws-sdk/client-ses';
import Email from '../../emails/email';
const ses = new SES({ region: process.env.AWS_SES_REGION })
const emailHtml = render(Email({ url:"https://example.com" }));
const params = {
Source: '[email protected]',
Destination: {
ToAddresses: ['[email protected]'],
},
Message: {
Body: {
Html: {
Charset: 'UTF-8',
Data: emailHtml,
},
},
Subject: {
Charset: 'UTF-8',
Data: 'hello world',
},
},
};
await ses.sendEmail(params);
Sources:
- Part one: React email docs - Manual setup
- Part two: React email docs - AWS SES integration