Skip to main content
SendGrid is a popular email delivery platform that provides reliable email sending with powerful APIs and comprehensive analytics.

Installation

1

Install dependencies

Install React Email components and the SendGrid SDK:
npm install react-email @react-email/components @sendgrid/mail
2

Set up your API key

Get your API key from SendGrid and add it to your environment variables:
SENDGRID_API_KEY=SG.xxx

Usage

Create an email component

emails/email.tsx
import { Button, Html } from '@react-email/components';

interface EmailProps {
  url: string;
}

export const Email: React.FC<Readonly<EmailProps>> = ({ url }) => {
  return (
    <Html lang="en">
      <Button href={url}>Click me</Button>
    </Html>
  );
};

Send the email

index.tsx
import { render } from '@react-email/components';
import sendgrid from '@sendgrid/mail';
import { Email } from './email';

sendgrid.setApiKey(process.env.SENDGRID_API_KEY || '');

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

const options = {
  from: '[email protected]',
  to: '[email protected]',
  subject: 'hello world',
  html: emailHtml,
};

await sendgrid.send(options);

Advanced features

Multiple recipients

await sendgrid.send({
  from: '[email protected]',
  to: ['[email protected]', '[email protected]'],
  subject: 'hello world',
  html: emailHtml,
});

CC and BCC

await sendgrid.send({
  from: '[email protected]',
  to: '[email protected]',
  cc: '[email protected]',
  bcc: ['[email protected]', '[email protected]'],
  subject: 'hello world',
  html: emailHtml,
});

Custom headers

await sendgrid.send({
  from: '[email protected]',
  to: '[email protected]',
  subject: 'hello world',
  html: emailHtml,
  headers: {
    'X-Custom-Header': 'Custom Value',
  },
});

Attachments

import fs from 'fs';

const attachment = fs.readFileSync('/path/to/file.pdf').toString('base64');

await sendgrid.send({
  from: '[email protected]',
  to: '[email protected]',
  subject: 'hello world',
  html: emailHtml,
  attachments: [
    {
      content: attachment,
      filename: 'document.pdf',
      type: 'application/pdf',
      disposition: 'attachment',
    },
  ],
});

Scheduled sending

const sendAt = Math.floor(Date.now() / 1000) + 3600; // 1 hour from now

await sendgrid.send({
  from: '[email protected]',
  to: '[email protected]',
  subject: 'hello world',
  html: emailHtml,
  sendAt: sendAt,
});

Error handling

try {
  await sendgrid.send(options);
  console.log('Email sent successfully');
} catch (error) {
  console.error('SendGrid error:', error);
  if (error.response) {
    console.error(error.response.body);
  }
}

Build docs developers (and LLMs) love