Kurs Next.js · Moduł 9: Integracje i zaawansowane funkcje

Next.js z Resend i React Email - Nowoczesny system mailowy

14 min czytania ·
W tej lekcji13

W Metropolii Quantum, gdzie komunikacja odbywa się z prędkością światła, poznasz połączenie Next.js z Resend i React Email - najnowocześniejszym stackiem do wysyłania emaili. Ta kombinacja pozwala tworzyć piękne, responsywne emaile i wysyłać je z niezawodnością enterprise-grade.

Czym jest Resend?

Resend to nowoczesna platforma do wysyłania emaili, stworzona przez zespół deweloperów dla deweloperów:

  • Developer Experience - czyste API i świetna dokumentacja
  • React Email integration - natywne wsparcie dla komponentów React
  • High deliverability - zaawansowane mechanizmy dostarczalności
  • Analytics - szczegółowe statystyki dostarczania
  • Webhooks - real-time powiadomienia o statusie emaili
  • Templates - system szablonów z React

Czym jest React Email?

React Email to biblioteka do tworzenia emaili przy użyciu React:

  • Component-based - tworzenie emaili jak zwykłych komponentów React
  • TypeScript support - pełne wsparcie typowania
  • Preview - podgląd emaili w przeglądarce
  • Cross-client compatibility - kompatybilność z wszystkimi klientami email
  • Export to HTML - konwersja do statycznego HTML

Instalacja i konfiguracja

Krok 1: Utworzenie konta Resend

  1. Zarejestruj się na resend.com
  2. Zweryfikuj domenę lub użyj domeny testowej
  3. Utwórz API key w Dashboard → API Keys

Krok 2: Instalacja pakietów

# Zainstaluj Resend i React Email
npm install resend react-email @react-email/components

# Dla development dodaj React Email CLI
npm install -D @react-email/cli

Krok 3: Konfiguracja zmiennych środowiskowych

Utwórz plik .env.local:

# Resend API Key
RESEND_API_KEY=re_123456789

# Email settings
FROM_EMAIL=noreply@yourdomain.com
REPLY_TO_EMAIL=support@yourdomain.com

Krok 4: Setup React Email

Dodaj skrypty do package.json:

{
  "scripts": {
    "email:dev": "email dev",
    "email:export": "email export"
  }
}

Utwórz konfigurację react-email.config.js:

module.exports = {
  outDir: './out',
  pretty: true,
  plainText: true,
};

Podstawowa integracja

Krok 1: Inicjalizacja Resend

Utwórz instancję Resend:

// 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);

Krok 2: Struktura folderów

Utwórz strukturę dla emaili:

emails/
├── components/
│   ├── Header.tsx
│   ├── Footer.tsx
│   └── Button.tsx
├── templates/
│   ├── welcome.tsx
│   ├── password-reset.tsx
│   └── order-confirmation.tsx
└── index.ts

Tworzenie komponentów emaili

Komponenty podstawowe

// 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}. Wszystkie prawa zastrzeżone.
      </Text>

      {address && (
        <Text style={addressStyle}>
          {address}
        </Text>
      )}

      {unsubscribeUrl && (
        <Text style={unsubscribeStyle}>
          <Link href={unsubscribeUrl} style={linkStyle}>
            Wypisz się z newslettera
          </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',
};

Szablony emaili

Email powitalny

// 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}>
              Witaj, {userFirstName}!
            </Heading>

            <Text style={textStyle}>
              Dziękujemy za rejestrację w {companyName}! Jesteśmy podekscytowani,
              że dołączyłeś do naszej społeczności.
            </Text>

            <Text style={textStyle}>
              Aby rozpocząć korzystanie z naszej platformy, kliknij poniższy przycisk:
            </Text>

            <Section style={buttonSectionStyle}>
              <Button href={loginUrl}>
                Zaloguj się do konta
              </Button>
            </Section>

            <Hr style={hrStyle} />

            <Text style={helpTextStyle}>
              Jeśli masz pytania, nie wahaj się <a href="mailto:support@example.com" style={linkStyle}>skontaktować z nami</a>.
            </Text>
          </Section>

          <Footer
            companyName={companyName}
            address="ul. Przykładowa 123, 00-000 Warszawa"
          />
        </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',
};

Email resetowania hasła

// 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}>
              Resetowanie hasła
            </Heading>

            <Text style={textStyle}>
              Cześć {userFirstName},
            </Text>

            <Text style={textStyle}>
              Otrzymaliśmy prośbę o zresetowanie hasła do Twojego konta w {companyName}.
              Jeśli to nie Ty, zignoruj tego emaila.
            </Text>

            <Section style={buttonSectionStyle}>
              <Button href={resetUrl}>
                Zresetuj hasło
              </Button>
            </Section>

            {resetCode && (
              <Section style={codeSectionStyle}>
                <Text style={codeTextStyle}>
                  Lub użyj tego kodu:
                </Text>
                <Code style={codeStyle}>{resetCode}</Code>
              </Section>
            )}

            <Text style={warningTextStyle}>
              Ten link wygaśnie za {expirationTime}.
            </Text>

            <Text style={securityTextStyle}>
              Ze względów bezpieczeństwa, jeśli nie prosiłeś o reset hasła,
              <a href="mailto:security@example.com" style={linkStyle}> skontaktuj się z nami natychmiast</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 dla wysyłania emaili

Podstawowe 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();

    // Walidacja podstawowa
    if (!type || !to || !data) {
      return NextResponse.json(
        { error: 'Missing required fields: type, to, data' },
        { status: 400 }
      );
    }

    let emailComponent;
    let subject;

    // Wybór szablonu na podstawie typu
    switch (type) {
      case 'welcome':
        emailComponent = WelcomeEmail({
          userFirstName: data.userFirstName,
          loginUrl: data.loginUrl,
          companyName: data.companyName || 'Nasza Firma',
        });
        subject = `Witaj w ${data.companyName || 'Naszej Firmie'}!`;
        break;

      case 'password-reset':
        emailComponent = PasswordResetEmail({
          userFirstName: data.userFirstName,
          resetUrl: data.resetUrl,
          resetCode: data.resetCode,
          companyName: data.companyName || 'Nasza Firma',
          expirationTime: data.expirationTime || '24 godziny',
        });
        subject = 'Resetowanie hasła';
        break;

      default:
        return NextResponse.json(
          { error: `Unknown email type: ${type}` },
          { status: 400 }
        );
    }

    // Wysłanie emaila
    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 }
    );
  }
}

Wysyłanie email z załącznikami

// 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,
    };

    // Dodanie załącznika jeśli istnieje
    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 || 'Nasza Firma',
    });

    return this.sendEmail(component, {
      ...options,
      subject: options.subject || `Witaj w ${data.companyName || 'Naszej Firmie'}!`,
    });
  }

  static async sendPasswordResetEmail(
    data: PasswordResetEmailData,
    options: EmailOptions
  ) {
    const component = PasswordResetEmail({
      ...data,
      companyName: data.companyName || 'Nasza Firma',
      expirationTime: data.expirationTime || '24 godziny',
    });

    return this.sendEmail(component, {
      ...options,
      subject: options.subject || 'Resetowanie hasła',
    });
  }

  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 dla integracji z komponentami

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 };
}

Przykład użycia w komponencie

// 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: 'Metropolia Quantum',
        },
      });

      alert('Email powitalny został wysłany!');
    } catch (error) {
      alert('Błąd podczas wysyłania emaila');
    }
  };

  return (
    <div>
      <button
        onClick={handleSendWelcomeEmail}
        disabled={loading}
        className="bg-blue-600 text-white px-4 py-2 rounded disabled:opacity-50"
      >
        {loading ? 'Wysyłanie...' : 'Wyślij email powitalny'}
      </button>

      {error && (
        <p className="text-red-600 text-sm mt-2">{error}</p>
      )}
    </div>
  );
}

Webhooks i analityka

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;

    // Logowanie eventów
    console.log(`Resend webhook: ${type}`, data);

    switch (type) {
      case 'email.sent':
        // Email został wysłany
        await handleEmailSent(data);
        break;

      case 'email.delivered':
        // Email został dostarczony
        await handleEmailDelivered(data);
        break;

      case 'email.bounced':
        // Email został odrzucony
        await handleEmailBounced(data);
        break;

      case 'email.complained':
        // Email został zgłoszony jako 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) {
  // Implementacja logiki po wysłaniu emaila
  console.log('Email sent:', data.email_id);
}

async function handleEmailDelivered(data: any) {
  // Implementacja logiki po dostarczeniu emaila
  console.log('Email delivered:', data.email_id);
}

async function handleEmailBounced(data: any) {
  // Implementacja logiki po odrzuceniu emaila
  console.log('Email bounced:', data.email_id, data.reason);

  // Możesz zaktualizować status użytkownika w bazie danych
  // await updateUserEmailStatus(data.to, 'bounced');
}

async function handleEmailComplained(data: any) {
  // Implementacja logiki po zgłoszeniu spamu
  console.log('Email complained:', data.email_id);

  // Automatyczne wypisanie z newslettera
  // await unsubscribeUser(data.to);
}

Development i testing

Preview emaili

Uruchom serwer preview:

npm run email:dev

Przejdź do http://localhost:3000 aby zobaczyć podgląd wszystkich emaili.

Export do HTML

npm run email:export

Testowanie w różnych klientach

// 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',
  }));

  // Zapisz HTML do pliku dla testów
  const fs = require('fs');
  fs.writeFileSync('./test-output/welcome-email.html', html);

  console.log('Email HTML generated for testing');
}

testEmailRendering();

Najlepsze praktyki

1. Personalizacja

// Zawsze używaj danych użytkownika
const personalizedSubject = `Cześć ${firstName}, sprawdź swoje nowe funkcje!`;

2. Responsive design

// Używaj responsywnych stylów
const responsiveStyle = {
  width: '100%',
  maxWidth: '600px',
  '@media (max-width: 600px)': {
    maxWidth: '100%',
    padding: '20px 10px',
  },
};

3. A/B testing

// Testuj różne wersje emaili
const subjectVariants = [
  'Witaj w naszej aplikacji!',
  'Twoje konto zostało utworzone',
  'Zaczynajmy przygodę razem!',
];

const randomSubject = subjectVariants[Math.floor(Math.random() * subjectVariants.length)];

4. Rate limiting

// Ogranicz liczbę emaili na użytkownika
const DAILY_EMAIL_LIMIT = 10;

async function checkEmailLimit(userId: string) {
  // Sprawdź ile emaili wysłano dzisiaj do tego użytkownika
  // Implementacja zależna od bazy danych
}

Podsumowanie

Połączenie Next.js z Resend i React Email tworzy potężny stack do wysyłania emaili:

  1. React Email - komponentowe tworzenie emaili
  2. Resend - niezawodne dostarczanie
  3. TypeScript - bezpieczeństwo typów
  4. Webhooks - real-time analytics
  5. Preview - łatwy development

Ta kombinacja pozwala budować profesjonalne systemy email marketingu, powiadomień transakcyjnych i komunikacji z użytkownikami.

Kod do tej lekcji: 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' }}>Witaj w Metropolii Quantum!</h1>
    </div>
    <div style={{ padding: '24px' }}>
      <p>Cześć <strong>{'{{name}}'}</strong>,</p>
      <p>Twoje konto zostało aktywowane. Oto jak zacząć:</p>
      <ol style={{ lineHeight: '2' }}>
        <li>Dokończ swój profil</li>
        <li>Zapoznaj się z dokumentacją</li>
        <li>Stwórz pierwszy projekt</li>
      </ol>
      <div style={{ textAlign: 'center', margin: '20px 0' }}>
        <span style={{ background: '#7c4dff', color: '#fff', padding: '12px 24px', borderRadius: '6px', display: 'inline-block' }}>Rozpocznij</span>
      </div>
    </div>
    <div style={{ background: '#f5f5f5', padding: '16px', textAlign: 'center', fontSize: '12px', color: '#888' }}>
      Metropolia Quantum © 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' }}>Reset hasła</h1>
    </div>
    <div style={{ padding: '24px' }}>
      <p>Otrzymaliśmy prośbę o zresetowanie hasła dla konta <strong>{'{{email}}'}</strong>.</p>
      <p>Kliknij poniższy przycisk, aby ustawić nowe hasło. Link wygasa za 24h.</p>
      <div style={{ textAlign: 'center', margin: '24px 0' }}>
        <span style={{ background: '#e94560', color: '#fff', padding: '12px 24px', borderRadius: '6px', display: 'inline-block' }}>Zresetuj hasło</span>
      </div>
      <p style={{ fontSize: '13px', color: '#888' }}>Jeśli nie prosiłeś o reset, zignoruj ten 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' }}>Potwierdzenie zamówienia</h1>
    </div>
    <div style={{ padding: '24px' }}>
      <p>Dziękujemy za zakup! Zamówienie <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' }}>Produkt</th>
          <th style={{ textAlign: 'right', padding: '8px' }}>Cena</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 PLN</td></tr>
          <tr style={{ borderBottom: '1px solid #eee' }}><td style={{ padding: '8px' }}>Cyber Toolkit</td><td style={{ textAlign: 'right', padding: '8px' }}>24.99 PLN</td></tr>
          <tr><td style={{ padding: '8px', fontWeight: 'bold' }}>Suma</td><td style={{ textAlign: 'right', padding: '8px', fontWeight: 'bold' }}>74.98 PLN</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: 'Witaj w Metropolii Quantum!', preview: <WelcomeEmailPreview /> },
    { id: 'reset', name: 'Password Reset', subject: 'Reset hasła', preview: <ResetPasswordPreview /> },
    { id: 'invoice', name: 'Order Confirmation', subject: 'Potwierdzenie zamówienia #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 ? 'Wysylanie...' : 'Wyslij 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;

Hasła z dokumentacji w tej lekcji

Widzisz błąd w tej lekcji?

Sprawdź się

Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.

  1. 1. React Email pozwala na:

  2. 2. Który zestaw komponentów NIE jest częścią biblioteki React Email?

Zadania praktyczne w grze

  • Klikanie w kolejności

    Uporządkuj kroki integracji Resend z Next.js.

  • Edytor kodu

    Stwórz komponent emailowy wykorzystując React Email z szablonem potwierdzenia zamówienia

  • Edytor kodu

    Zbuduj welcome email z React Email components.

  1. PytanieReact Email
  2. PytanieReact Email komponenty
  3. Kliknij w kolejnościResend API integration
  4. Zadanie z kodemPraktyka: System emailowy z React Email
  5. Zadanie z kodemEmail templates z React Email

Przydatne artykuły