Next.js course Β· Module 9: Integrations and Advanced Features
Next.js with Resend and React Email - A Modern Email System
In this lesson13
In Quantum Metropolis, where communication happens at the speed of light, you will discover the combination of Next.js with Resend and React Email - the most modern stack for sending emails. This combination allows you to create beautiful, responsive emails and send them with enterprise-grade reliability.
What is Resend?
Resend is a modern email sending platform, created by a team of developers for developers:
- Developer Experience - clean API and excellent documentation
- React Email integration - native support for React components
- High deliverability - advanced deliverability mechanisms
- Analytics - detailed delivery statistics
- Webhooks - real-time notifications about email status
- Templates - template system with React
What is React Email?
React Email is a library for creating emails using React:
- Component-based - creating emails like regular React components
- TypeScript support - full type support
- Preview - email preview in the browser
- Cross-client compatibility - compatibility with all email clients
- Export to HTML - conversion to static HTML
Installation and configuration
Step 1: Create a Resend account
- Sign up at resend.com
- Verify your domain or use a test domain
- Create an API key in Dashboard β API Keys
Step 2: Package installation
# Install Resend and React Email
npm install resend react-email @react-email/components
# For development add React Email CLI
npm install -D @react-email/cliStep 3: Environment variables configuration
Create the file .env.local:
# Resend API Key
RESEND_API_KEY=re_123456789
# Email settings
FROM_EMAIL=noreply@yourdomain.com
REPLY_TO_EMAIL=support@yourdomain.comStep 4: Setup React Email
Add scripts to package.json:
{
"scripts": {
"email:dev": "email dev",
"email:export": "email export"
}
}Create the react-email.config.js configuration:
module.exports = {
outDir: './out',
pretty: true,
plainText: true,
};Basic integration
Step 1: Initializing Resend
Create a Resend instance:
// lib/resend.ts
import { Resend } from 'resend';
if (!process.env.RESEND_API_KEY) {
throw new Error('RESEND_API_KEY is not defined');
}
export const resend = new Resend(process.env.RESEND_API_KEY);Step 2: Folder structure
Create the structure for emails:
emails/
βββ components/
β βββ Header.tsx
β βββ Footer.tsx
β βββ Button.tsx
βββ templates/
β βββ welcome.tsx
β βββ password-reset.tsx
β βββ order-confirmation.tsx
βββ index.tsCreating email components
Basic components
// emails/components/Header.tsx
import { Img, Section, Text } from '@react-email/components';
interface HeaderProps {
logoUrl?: string;
companyName: string;
}
export function Header({ logoUrl, companyName }: HeaderProps) {
return (
<Section style={headerStyle}>
{logoUrl && (
<Img
src={logoUrl}
width="150"
height="50"
alt={companyName}
style={logoStyle}
/>
)}
<Text style={companyStyle}>{companyName}</Text>
</Section>
);
}
const headerStyle = {
backgroundColor: '#f8f9fa',
padding: '20px',
textAlign: 'center' as const,
};
const logoStyle = {
margin: '0 auto',
marginBottom: '10px',
};
const companyStyle = {
fontSize: '24px',
fontWeight: 'bold',
color: '#333333',
margin: '0',
};// emails/components/Button.tsx
import { Button as EmailButton } from '@react-email/components';
interface ButtonProps {
href: string;
children: React.ReactNode;
variant?: 'primary' | 'secondary';
}
export function Button({ href, children, variant = 'primary' }: ButtonProps) {
const style = variant === 'primary' ? primaryButtonStyle : secondaryButtonStyle;
return (
<EmailButton href={href} style={style}>
{children}
</EmailButton>
);
}
const primaryButtonStyle = {
backgroundColor: '#007bff',
color: '#ffffff',
padding: '12px 24px',
borderRadius: '6px',
textDecoration: 'none',
display: 'inline-block',
fontWeight: 'bold',
};
const secondaryButtonStyle = {
backgroundColor: '#6c757d',
color: '#ffffff',
padding: '12px 24px',
borderRadius: '6px',
textDecoration: 'none',
display: 'inline-block',
fontWeight: 'bold',
};// emails/components/Footer.tsx
import { Section, Text, Link } from '@react-email/components';
interface FooterProps {
companyName: string;
unsubscribeUrl?: string;
address?: string;
}
export function Footer({ companyName, unsubscribeUrl, address }: FooterProps) {
return (
<Section style={footerStyle}>
<Text style={footerTextStyle}>
Β© 2024 {companyName}. All rights reserved.
</Text>
{address && (
<Text style={addressStyle}>
{address}
</Text>
)}
{unsubscribeUrl && (
<Text style={unsubscribeStyle}>
<Link href={unsubscribeUrl} style={linkStyle}>
Unsubscribe from newsletter
</Link>
</Text>
)}
</Section>
);
}
const footerStyle = {
backgroundColor: '#f8f9fa',
padding: '20px',
textAlign: 'center' as const,
marginTop: '40px',
};
const footerTextStyle = {
fontSize: '14px',
color: '#6c757d',
margin: '0 0 10px',
};
const addressStyle = {
fontSize: '12px',
color: '#6c757d',
margin: '0 0 10px',
};
const unsubscribeStyle = {
fontSize: '12px',
color: '#6c757d',
margin: '0',
};
const linkStyle = {
color: '#007bff',
textDecoration: 'underline',
};Email templates
Welcome email
// emails/templates/welcome.tsx
import {
Html,
Head,
Body,
Container,
Section,
Text,
Heading,
Hr,
} from '@react-email/components';
import { Header } from '../components/Header';
import { Button } from '../components/Button';
import { Footer } from '../components/Footer';
interface WelcomeEmailProps {
userFirstName: string;
loginUrl: string;
companyName: string;
}
export default function WelcomeEmail({
userFirstName,
loginUrl,
companyName,
}: WelcomeEmailProps) {
return (
<Html>
<Head />
<Body style={bodyStyle}>
<Container style={containerStyle}>
<Header companyName={companyName} />
<Section style={contentStyle}>
<Heading style={headingStyle}>
Hello, {userFirstName}!
</Heading>
<Text style={textStyle}>
Thanks for signing up to {companyName}! We are excited
that you have joined our community.
</Text>
<Text style={textStyle}>
To start using our platform, click the button below:
</Text>
<Section style={buttonSectionStyle}>
<Button href={loginUrl}>
Log in to your account
</Button>
</Section>
<Hr style={hrStyle} />
<Text style={helpTextStyle}>
If you have questions, feel free to <a href="mailto:support@example.com" style={linkStyle}>contact us</a>.
</Text>
</Section>
<Footer
companyName={companyName}
address="123 Example St, 00-000 Warsaw"
/>
</Container>
</Body>
</Html>
);
}
const bodyStyle = {
backgroundColor: '#ffffff',
fontFamily: 'Arial, sans-serif',
};
const containerStyle = {
maxWidth: '600px',
margin: '0 auto',
};
const contentStyle = {
padding: '40px 20px',
};
const headingStyle = {
fontSize: '28px',
color: '#333333',
textAlign: 'center' as const,
marginBottom: '30px',
};
const textStyle = {
fontSize: '16px',
color: '#333333',
lineHeight: '1.6',
marginBottom: '20px',
};
const buttonSectionStyle = {
textAlign: 'center' as const,
marginTop: '30px',
marginBottom: '30px',
};
const hrStyle = {
borderColor: '#e9ecef',
margin: '30px 0',
};
const helpTextStyle = {
fontSize: '14px',
color: '#6c757d',
textAlign: 'center' as const,
};
const linkStyle = {
color: '#007bff',
textDecoration: 'underline',
};Password reset email
// emails/templates/password-reset.tsx
import {
Html,
Head,
Body,
Container,
Section,
Text,
Heading,
Code,
} from '@react-email/components';
import { Header } from '../components/Header';
import { Button } from '../components/Button';
import { Footer } from '../components/Footer';
interface PasswordResetEmailProps {
userFirstName: string;
resetUrl: string;
resetCode?: string;
companyName: string;
expirationTime: string;
}
export default function PasswordResetEmail({
userFirstName,
resetUrl,
resetCode,
companyName,
expirationTime,
}: PasswordResetEmailProps) {
return (
<Html>
<Head />
<Body style={bodyStyle}>
<Container style={containerStyle}>
<Header companyName={companyName} />
<Section style={contentStyle}>
<Heading style={headingStyle}>
Password reset
</Heading>
<Text style={textStyle}>
Hello {userFirstName},
</Text>
<Text style={textStyle}>
We received a request to reset the password for your account at {companyName}.
If it wasn't you, ignore this email.
</Text>
<Section style={buttonSectionStyle}>
<Button href={resetUrl}>
Reset password
</Button>
</Section>
{resetCode && (
<Section style={codeSectionStyle}>
<Text style={codeTextStyle}>
Or use this code:
</Text>
<Code style={codeStyle}>{resetCode}</Code>
</Section>
)}
<Text style={warningTextStyle}>
This link will expire in {expirationTime}.
</Text>
<Text style={securityTextStyle}>
For security reasons, if you did not request a password reset,
<a href="mailto:security@example.com" style={linkStyle}> contact us immediately</a>.
</Text>
</Section>
<Footer companyName={companyName} />
</Container>
</Body>
</Html>
);
}
const bodyStyle = {
backgroundColor: '#ffffff',
fontFamily: 'Arial, sans-serif',
};
const containerStyle = {
maxWidth: '600px',
margin: '0 auto',
};
const contentStyle = {
padding: '40px 20px',
};
const headingStyle = {
fontSize: '28px',
color: '#333333',
textAlign: 'center' as const,
marginBottom: '30px',
};
const textStyle = {
fontSize: '16px',
color: '#333333',
lineHeight: '1.6',
marginBottom: '20px',
};
const buttonSectionStyle = {
textAlign: 'center' as const,
marginTop: '30px',
marginBottom: '30px',
};
const codeSectionStyle = {
textAlign: 'center' as const,
marginBottom: '30px',
padding: '20px',
backgroundColor: '#f8f9fa',
borderRadius: '8px',
};
const codeTextStyle = {
fontSize: '14px',
color: '#6c757d',
marginBottom: '10px',
};
const codeStyle = {
fontSize: '24px',
fontWeight: 'bold',
letterSpacing: '4px',
color: '#007bff',
};
const warningTextStyle = {
fontSize: '14px',
color: '#dc3545',
textAlign: 'center' as const,
marginBottom: '20px',
padding: '15px',
backgroundColor: '#f8d7da',
borderRadius: '6px',
};
const securityTextStyle = {
fontSize: '12px',
color: '#6c757d',
textAlign: 'center' as const,
};
const linkStyle = {
color: '#007bff',
textDecoration: 'underline',
};API Routes for sending emails
Basic API
// app/api/send-email/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { resend } from '@/lib/resend';
import WelcomeEmail from '@/emails/templates/welcome';
import PasswordResetEmail from '@/emails/templates/password-reset';
export async function POST(request: NextRequest) {
try {
const { type, to, data } = await request.json();
// Basic validation
if (!type || !to || !data) {
return NextResponse.json(
{ error: 'Missing required fields: type, to, data' },
{ status: 400 }
);
}
let emailComponent;
let subject;
// Template selection based on type
switch (type) {
case 'welcome':
emailComponent = WelcomeEmail({
userFirstName: data.userFirstName,
loginUrl: data.loginUrl,
companyName: data.companyName || 'Our Company',
});
subject = `Welcome to ${data.companyName || 'Our Company'}!`;
break;
case 'password-reset':
emailComponent = PasswordResetEmail({
userFirstName: data.userFirstName,
resetUrl: data.resetUrl,
resetCode: data.resetCode,
companyName: data.companyName || 'Our Company',
expirationTime: data.expirationTime || '24 hours',
});
subject = 'Password reset';
break;
default:
return NextResponse.json(
{ error: `Unknown email type: ${type}` },
{ status: 400 }
);
}
// Sending the email
const result = await resend.emails.send({
from: process.env.FROM_EMAIL!,
to: Array.isArray(to) ? to : [to],
subject,
react: emailComponent,
replyTo: process.env.REPLY_TO_EMAIL,
});
return NextResponse.json({
success: true,
messageId: result.data?.id
});
} catch (error) {
console.error('Email sending error:', error);
return NextResponse.json(
{ error: 'Failed to send email' },
{ status: 500 }
);
}
}Sending an email with attachments
// app/api/send-email-with-attachment/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { resend } from '@/lib/resend';
export async function POST(request: NextRequest) {
try {
const formData = await request.formData();
const to = formData.get('to') as string;
const subject = formData.get('subject') as string;
const htmlContent = formData.get('html') as string;
const attachment = formData.get('attachment') as File;
if (!to || !subject || !htmlContent) {
return NextResponse.json(
{ error: 'Missing required fields' },
{ status: 400 }
);
}
const emailData: any = {
from: process.env.FROM_EMAIL!,
to: [to],
subject,
html: htmlContent,
};
// Adding an attachment if one exists
if (attachment) {
const buffer = await attachment.arrayBuffer();
emailData.attachments = [
{
filename: attachment.name,
content: Buffer.from(buffer),
},
];
}
const result = await resend.emails.send(emailData);
return NextResponse.json({
success: true,
messageId: result.data?.id
});
} catch (error) {
console.error('Email sending error:', error);
return NextResponse.json(
{ error: 'Failed to send email' },
{ status: 500 }
);
}
}Utility functions
Email service
// lib/email-service.ts
import { resend } from '@/lib/resend';
import WelcomeEmail from '@/emails/templates/welcome';
import PasswordResetEmail from '@/emails/templates/password-reset';
interface EmailOptions {
to: string | string[];
subject?: string;
replyTo?: string;
}
interface WelcomeEmailData {
userFirstName: string;
loginUrl: string;
companyName?: string;
}
interface PasswordResetEmailData {
userFirstName: string;
resetUrl: string;
resetCode?: string;
companyName?: string;
expirationTime?: string;
}
export class EmailService {
private static async sendEmail(
component: React.ReactElement,
options: EmailOptions
) {
try {
const result = await resend.emails.send({
from: process.env.FROM_EMAIL!,
to: Array.isArray(options.to) ? options.to : [options.to],
subject: options.subject!,
react: component,
replyTo: options.replyTo || process.env.REPLY_TO_EMAIL,
});
return { success: true, messageId: result.data?.id };
} catch (error) {
console.error('Email sending failed:', error);
throw new Error('Failed to send email');
}
}
static async sendWelcomeEmail(
data: WelcomeEmailData,
options: EmailOptions
) {
const component = WelcomeEmail({
...data,
companyName: data.companyName || 'Our Company',
});
return this.sendEmail(component, {
...options,
subject: options.subject || `Welcome to ${data.companyName || 'Our Company'}!`,
});
}
static async sendPasswordResetEmail(
data: PasswordResetEmailData,
options: EmailOptions
) {
const component = PasswordResetEmail({
...data,
companyName: data.companyName || 'Our Company',
expirationTime: data.expirationTime || '24 hours',
});
return this.sendEmail(component, {
...options,
subject: options.subject || 'Password reset',
});
}
static async sendBulkEmails(
recipients: string[],
component: React.ReactElement,
subject: string
) {
const promises = recipients.map(email =>
this.sendEmail(component, { to: email, subject })
);
try {
const results = await Promise.allSettled(promises);
const successful = results.filter(r => r.status === 'fulfilled').length;
const failed = results.filter(r => r.status === 'rejected').length;
return { successful, failed, total: recipients.length };
} catch (error) {
throw new Error('Bulk email sending failed');
}
}
}Email validation
// lib/email-validation.ts
import { z } from 'zod';
export const emailSchema = z.object({
type: z.enum(['welcome', 'password-reset', 'order-confirmation']),
to: z.union([
z.string().email(),
z.array(z.string().email()).min(1)
]),
data: z.object({
userFirstName: z.string().min(1),
companyName: z.string().optional(),
}).and(
z.union([
z.object({
loginUrl: z.string().url(),
}),
z.object({
resetUrl: z.string().url(),
resetCode: z.string().optional(),
expirationTime: z.string().optional(),
}),
])
),
});
export function validateEmailRequest(data: unknown) {
return emailSchema.parse(data);
}Hooks for component integration
useEmailSender hook
// hooks/useEmailSender.ts
import { useState } from 'react';
interface EmailData {
type: string;
to: string | string[];
data: Record<string, any>;
}
export function useEmailSender() {
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const sendEmail = async (emailData: EmailData) => {
setLoading(true);
setError(null);
try {
const response = await fetch('/api/send-email', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(emailData),
});
const result = await response.json();
if (!response.ok) {
throw new Error(result.error || 'Failed to send email');
}
return result;
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
setError(errorMessage);
throw err;
} finally {
setLoading(false);
}
};
return { sendEmail, loading, error };
}Example usage in a component
// components/WelcomeEmailButton.tsx
'use client';
import { useEmailSender } from '@/hooks/useEmailSender';
interface WelcomeEmailButtonProps {
userEmail: string;
userFirstName: string;
}
export function WelcomeEmailButton({ userEmail, userFirstName }: WelcomeEmailButtonProps) {
const { sendEmail, loading, error } = useEmailSender();
const handleSendWelcomeEmail = async () => {
try {
await sendEmail({
type: 'welcome',
to: userEmail,
data: {
userFirstName,
loginUrl: `${window.location.origin}/login`,
companyName: 'Metropolis Quantum',
},
});
alert('Welcome email has been sent!');
} catch (error) {
alert('Error while sending email');
}
};
return (
<div>
<button
onClick={handleSendWelcomeEmail}
disabled={loading}
className="bg-blue-600 text-white px-4 py-2 rounded disabled:opacity-50"
>
{loading ? 'Sending...' : 'Send welcome email'}
</button>
{error && (
<p className="text-red-600 text-sm mt-2">{error}</p>
)}
</div>
);
}Webhooks and analytics
Webhook handler
// app/api/webhooks/resend/route.ts
import { NextRequest, NextResponse } from 'next/server';
export async function POST(request: NextRequest) {
try {
const payload = await request.json();
const { type, data } = payload;
// Event logging
console.log(`Resend webhook: ${type}`, data);
switch (type) {
case 'email.sent':
// Email has been sent
await handleEmailSent(data);
break;
case 'email.delivered':
// Email has been delivered
await handleEmailDelivered(data);
break;
case 'email.bounced':
// Email has bounced
await handleEmailBounced(data);
break;
case 'email.complained':
// Email was reported as spam
await handleEmailComplained(data);
break;
default:
console.log(`Unhandled webhook type: ${type}`);
}
return NextResponse.json({ received: true });
} catch (error) {
console.error('Webhook error:', error);
return NextResponse.json(
{ error: 'Webhook processing failed' },
{ status: 500 }
);
}
}
async function handleEmailSent(data: any) {
// Logic after email has been sent
console.log('Email sent:', data.email_id);
}
async function handleEmailDelivered(data: any) {
// Logic after email has been delivered
console.log('Email delivered:', data.email_id);
}
async function handleEmailBounced(data: any) {
// Logic after email has bounced
console.log('Email bounced:', data.email_id, data.reason);
// You can update user status in the database
// await updateUserEmailStatus(data.to, 'bounced');
}
async function handleEmailComplained(data: any) {
// Logic after spam report
console.log('Email complained:', data.email_id);
// Automatic unsubscribe from the newsletter
// await unsubscribeUser(data.to);
}Development and testing
Email preview
Start the preview server:
npm run email:devGo to http://localhost:3000 to preview all emails.
Export to HTML
npm run email:exportTesting in various clients
// scripts/test-email-clients.ts
import { render } from '@react-email/render';
import WelcomeEmail from '../emails/templates/welcome';
async function testEmailRendering() {
const html = render(WelcomeEmail({
userFirstName: 'Jan',
loginUrl: 'https://example.com/login',
companyName: 'Test Company',
}));
// Save HTML to file for testing
const fs = require('fs');
fs.writeFileSync('./test-output/welcome-email.html', html);
console.log('Email HTML generated for testing');
}
testEmailRendering();Best practices
1. Personalization
// Always use user data
const personalizedSubject = `Hi ${firstName}, check out your new features!`;2. Responsive design
// Use responsive styles
const responsiveStyle = {
width: '100%',
maxWidth: '600px',
'@media (max-width: 600px)': {
maxWidth: '100%',
padding: '20px 10px',
},
};3. A/B testing
// Test different email versions
const subjectVariants = [
'Welcome to our application!',
'Your account has been created',
'Let us begin the adventure together!',
];
const randomSubject = subjectVariants[Math.floor(Math.random() * subjectVariants.length)];4. Rate limiting
// Limit the number of emails per user
const DAILY_EMAIL_LIMIT = 10;
async function checkEmailLimit(userId: string) {
// Check how many emails have been sent today to this user
// Implementation depends on the database
}Summary
Combining Next.js with Resend and React Email creates a powerful stack for sending emails:
- React Email - component-based email creation
- Resend - reliable delivery
- TypeScript - type safety
- Webhooks - real-time analytics
- Preview - easy development
This combination lets you build professional email marketing systems, transactional notifications, and user communications.
Code for this lesson: App.tsx
import React, { useState } from 'react';
interface EmailTemplate {
id: string;
name: string;
subject: string;
preview: React.ReactNode;
}
const WelcomeEmailPreview = () => (
<div style={{ fontFamily: 'Arial, sans-serif', maxWidth: '500px', margin: '0 auto', background: '#fff', color: '#333', borderRadius: '8px', overflow: 'hidden' }}>
<div style={{ background: 'linear-gradient(135deg, #7c4dff, #64ffda)', padding: '30px', textAlign: 'center' }}>
<h1 style={{ color: '#fff', margin: 0, fontSize: '24px' }}>Welcome to Quantum Metropolis!</h1>
</div>
<div style={{ padding: '24px' }}>
<p>Hello <strong>{'{{name}}'}</strong>,</p>
<p>Your account has been activated. Here is how to get started:</p>
<ol style={{ lineHeight: '2' }}>
<li>Complete your profile</li>
<li>Review the documentation</li>
<li>Create your first project</li>
</ol>
<div style={{ textAlign: 'center', margin: '20px 0' }}>
<span style={{ background: '#7c4dff', color: '#fff', padding: '12px 24px', borderRadius: '6px', display: 'inline-block' }}>Get Started</span>
</div>
</div>
<div style={{ background: '#f5f5f5', padding: '16px', textAlign: 'center', fontSize: '12px', color: '#888' }}>
Quantum Metropolis Β© 2025
</div>
</div>
);
const ResetPasswordPreview = () => (
<div style={{ fontFamily: 'Arial, sans-serif', maxWidth: '500px', margin: '0 auto', background: '#fff', color: '#333', borderRadius: '8px', overflow: 'hidden' }}>
<div style={{ background: '#e94560', padding: '24px', textAlign: 'center' }}>
<h1 style={{ color: '#fff', margin: 0, fontSize: '20px' }}>Password Reset</h1>
</div>
<div style={{ padding: '24px' }}>
<p>We received a request to reset the password for account <strong>{'{{email}}'}</strong>.</p>
<p>Click the button below to set a new password. The link expires in 24h.</p>
<div style={{ textAlign: 'center', margin: '24px 0' }}>
<span style={{ background: '#e94560', color: '#fff', padding: '12px 24px', borderRadius: '6px', display: 'inline-block' }}>Reset Password</span>
</div>
<p style={{ fontSize: '13px', color: '#888' }}>If you did not request a reset, ignore this email.</p>
</div>
</div>
);
const InvoicePreview = () => (
<div style={{ fontFamily: 'Arial, sans-serif', maxWidth: '500px', margin: '0 auto', background: '#fff', color: '#333', borderRadius: '8px', overflow: 'hidden' }}>
<div style={{ background: '#0f3460', padding: '24px', textAlign: 'center' }}>
<h1 style={{ color: '#fff', margin: 0, fontSize: '20px' }}>Order Confirmation</h1>
</div>
<div style={{ padding: '24px' }}>
<p>Thank you for your purchase! Order <strong>#QM-2025-0042</strong></p>
<table style={{ width: '100%', borderCollapse: 'collapse', marginTop: '16px' }}>
<thead><tr style={{ borderBottom: '2px solid #eee' }}>
<th style={{ textAlign: 'left', padding: '8px' }}>Product</th>
<th style={{ textAlign: 'right', padding: '8px' }}>Price</th>
</tr></thead>
<tbody>
<tr style={{ borderBottom: '1px solid #eee' }}><td style={{ padding: '8px' }}>Quantum Shield Pro</td><td style={{ textAlign: 'right', padding: '8px' }}>49.99 CR</td></tr>
<tr style={{ borderBottom: '1px solid #eee' }}><td style={{ padding: '8px' }}>Cyber Toolkit</td><td style={{ textAlign: 'right', padding: '8px' }}>24.99 CR</td></tr>
<tr><td style={{ padding: '8px', fontWeight: 'bold' }}>Total</td><td style={{ textAlign: 'right', padding: '8px', fontWeight: 'bold' }}>74.98 CR</td></tr>
</tbody>
</table>
</div>
</div>
);
const ResendDemo = () => {
const [selectedTemplate, setSelectedTemplate] = useState<string>('welcome');
const [sending, setSending] = useState(false);
const [logs, setLogs] = useState<string[]>([]);
const templates: EmailTemplate[] = [
{ id: 'welcome', name: 'Welcome Email', subject: 'Welcome to Quantum Metropolis!', preview: <WelcomeEmailPreview /> },
{ id: 'reset', name: 'Password Reset', subject: 'Password Reset', preview: <ResetPasswordPreview /> },
{ id: 'invoice', name: 'Order Confirmation', subject: 'Order Confirmation #QM-2025-0042', preview: <InvoicePreview /> },
];
const currentTemplate = templates.find(t => t.id === selectedTemplate)!;
const handleSend = async () => {
setSending(true);
setLogs([]);
const addLog = (msg: string) => setLogs(prev => [...prev, msg]);
addLog('POST /api/send - Sending email via Resend...');
await new Promise(r => setTimeout(r, 400));
addLog('resend.emails.send({ from: "noreply@quantum.city", to: "user@example.com" })');
await new Promise(r => setTimeout(r, 500));
addLog('React Email template rendered to HTML');
await new Promise(r => setTimeout(r, 300));
addLog('Response: { id: "re_abc123", statusCode: 200 }');
addLog('Email delivered successfully!');
setSending(false);
};
return (
<div style={{ background: '#0f0f23', minHeight: '100vh', padding: '20px', color: '#fff', fontFamily: 'sans-serif' }}>
<h1 style={{ color: '#64ffda', textAlign: 'center' }}>Next.js + Resend + React Email</h1>
<div style={{ maxWidth: '800px', margin: '20px auto' }}>
<div style={{ display: 'flex', gap: '8px', marginBottom: '16px', justifyContent: 'center' }}>
{templates.map(t => (
<button key={t.id} onClick={() => { setSelectedTemplate(t.id); setLogs([]); }}
style={{ padding: '8px 16px', background: selectedTemplate === t.id ? '#7c4dff' : 'rgba(255,255,255,0.1)', border: 'none', borderRadius: '6px', color: '#fff', cursor: 'pointer' }}>
{t.name}
</button>
))}
</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
<div>
<h3 style={{ color: '#7c4dff', marginBottom: '10px' }}>Email Preview</h3>
<div style={{ borderRadius: '10px', overflow: 'hidden', border: '1px solid #333' }}>
{currentTemplate.preview}
</div>
</div>
<div>
<h3 style={{ color: '#7c4dff', marginBottom: '10px' }}>API Console</h3>
<div style={{ background: 'rgba(255,255,255,0.05)', padding: '16px', borderRadius: '10px', border: '1px solid #333' }}>
<p style={{ color: '#888', fontSize: '13px', marginBottom: '8px' }}>Subject: {currentTemplate.subject}</p>
<button onClick={handleSend} disabled={sending}
style={{ width: '100%', padding: '10px', background: sending ? '#555' : '#64ffda', border: 'none', borderRadius: '6px', color: '#0f0f23', fontWeight: 'bold', cursor: sending ? 'default' : 'pointer' }}>
{sending ? 'Sending...' : 'Send email'}
</button>
</div>
{logs.length > 0 && (
<div style={{ background: '#000', padding: '12px', borderRadius: '8px', marginTop: '10px', fontFamily: 'monospace', fontSize: '11px' }}>
{logs.map((log, i) => (<div key={i} style={{ color: '#0f0', padding: '2px 0' }}>{log}</div>))}
</div>
)}
</div>
</div>
</div>
</div>
);
};
export default ResendDemo;Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. React Email allows you to:
2. Which set of components is NOT part of the React Email library?
Hands-on tasks in the game
- Click in order
Arrange the steps of integrating Resend with Next.js in order.
- Code editor
Create an email component using React Email with an order confirmation template
- Code editor
Build a welcome email with React Email components.