Skip to main content

1. Install dependencies

Get the react-email, mailgun.js, and form-data packages.
npm install mailgun.js form-data react-email

2. Create an email using React

Start by building your email template in a .jsx or .tsx file.
email.tsx
import { Button, Html } from 'react-email';

interface EmailProps {
  url: string;
}

export function Email({ url }: EmailProps) {
  return (
    <Html lang="en">
      <Button href={url}>Click me</Button>
    </Html>
  );
}

3. Convert to HTML and send email

Import the email template you just built, convert it into an HTML string, and use the Mailgun SDK to send it.
import { render } from 'react-email';
import FormData from 'form-data';
import Mailgun from 'mailgun.js';
import { Email } from './email';

const mailgun = new Mailgun(FormData);
const client = mailgun.client({
  username: 'api',
  key: process.env.MAILGUN_API_KEY,
});

const emailHtml = await render(<Email url="https://example.com" />);

await client.messages.create(process.env.MAILGUN_DOMAIN, {
  from: 'you@example.com',
  to: ['user@gmail.com'],
  subject: 'hello world',
  html: emailHtml,
});

Try it yourself

Mailgun example

See the full source code.