First add your dependencies

1
  npm i react-email @react-email/components resend -E

Create a new folder to store the emails. This lives next to my app directory.

1
  mkdir -p src/emails

Add a script in package.json to help with testing:

1
2
3
4
5
  {
      "scripts": {
          "email": "email dev --dir ./src/emails"
      }
  }

Create the email

I'm going to copy an example over from https://www.reactemailtemplate.com/components/articles since this is just demonstration.

Lets put something in src/emails/welcome.tsx

Start up the email dev server to see if you like it, and edit it however you'd like.

1
  npm run email

Create a send email action

This is here to organize the code, and will be invoked by the server.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
  // src/app/actions.tsx

  import { Resend } from 'resend';
  import WelcomeEmail from '../emails/welcome';

  export async function sendWelcomeEmail(email: string) {
    if (process.env.RESEND_API === undefined) {
      console.log('Please set RESEND_API');
      process.exit(1);
    }

    const resend = new Resend(process.env.RESEND_API);

    const result = await resend.emails.send({
      from: 'onboarding@resend.dev',
      to: email,
      subject: 'Test email',
      react: <WelcomeEmail />,
    });

    console.log('Email sent', result);
  }

Write a test page

This using server compoent actions. The sendEmail method will be invoked on the server, which has access to the api key.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  // src/app/email/page.tsx
  import { sendWelcomeEmail } from '../actions';

  export default function Page() {
    const sendEmail = async (formData: FormData) => {
      'use server';

      const email = formData.get('email');
      if (email) {
        console.log('sending email to', email);
        await sendWelcomeEmail(email as string);
      } else {
        console.log('Email not set');
      }
    };
    return (
      <main className='flex min-h-screen flex-col items-center justify-between p-24'>
        <div className='overflow-hidden px-4 py-2 rounded-lg bg-white shadow'>
          <form action={sendEmail} method='POST'>
            <label htmlFor='email'>Email</label>
            <input type='email' id='email' name='email' />
            <button type='submit'>Submit</button>
          </form>
        </div>
      </main>
    );
  }

Deploying to vercel

Add RESEND_API to the environment, and then just push and test it out.

This is my first time using server components, and it's confusing but pretty nifty.