Installation
Set up your API key
Get your API key from SendGrid and add it to your environment variables:
Usage
Create an email component
emails/email.tsx
Send the email
index.tsx
Powered by Mintlify
Auto-generate your docs
Send emails with React Email using SendGrid
Install dependencies
npm install react-email @react-email/components @sendgrid/mail
Set up your API key
SENDGRID_API_KEY=SG.xxx
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>
);
};
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);
await sendgrid.send({
from: '[email protected]',
to: ['[email protected]', '[email protected]'],
subject: 'hello world',
html: emailHtml,
});
await sendgrid.send({
from: '[email protected]',
to: '[email protected]',
cc: '[email protected]',
bcc: ['[email protected]', '[email protected]'],
subject: 'hello world',
html: emailHtml,
});
await sendgrid.send({
from: '[email protected]',
to: '[email protected]',
subject: 'hello world',
html: emailHtml,
headers: {
'X-Custom-Header': 'Custom Value',
},
});
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',
},
],
});
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,
});
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);
}
}