Use Cases

Como implementar envio de correos electronicos eficientemente con Claude Code

Aprenda a implementar envio de correos electronicos eficientemente usando Claude Code. Incluye ejemplos practicos de codigo y guia paso a paso.

Ventajas de usar Claude Code para implementar funcionalidad de correo

La funcionalidad de envio de correos tiene muchas consideraciones: creacion de plantillas, logica de envio, manejo de errores y procesamiento de reintentos. Claude Code implementa todo esto de manera integral y propone una estructura que se puede probar.

Envio basico de correos con Resend

> Crea un servicio de envio de correos usando Resend.
> Gestiona las plantillas con React Email.
> Implementa tambien reintentos y manejo de errores.
// src/services/email-service.ts
import { Resend } from 'resend';

const resend = new Resend(process.env.RESEND_API_KEY);

interface SendEmailOptions {
  to: string | string[];
  subject: string;
  html: string;
  text?: string;
  replyTo?: string;
}

export class EmailService {
  private maxRetries = 3;

  async send(options: SendEmailOptions): Promise<{ id: string }> {
    let lastError: Error | null = null;

    for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
      try {
        const { data, error } = await resend.emails.send({
          from: 'MyApp <[email protected]>',
          to: options.to,
          subject: options.subject,
          html: options.html,
          text: options.text,
          replyTo: options.replyTo,
        });

        if (error) throw new Error(error.message);
        return { id: data!.id };
      } catch (err) {
        lastError = err as Error;
        if (attempt < this.maxRetries) {
          await this.delay(1000 * attempt); // Backoff exponencial
        }
      }
    }

    throw new Error(`Fallo despues de ${this.maxRetries} intentos: ${lastError?.message}`);
  }

  private delay(ms: number) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}

Creacion de plantillas con React Email

// emails/welcome.tsx
import {
  Body,
  Container,
  Head,
  Heading,
  Html,
  Link,
  Preview,
  Section,
  Text,
} from '@react-email/components';

interface WelcomeEmailProps {
  userName: string;
  loginUrl: string;
}

export function WelcomeEmail({ userName, loginUrl }: WelcomeEmailProps) {
  return (
    <Html>
      <Head />
      <Preview>Bienvenido, {userName}!</Preview>
      <Body style={{ backgroundColor: '#f6f9fc', fontFamily: 'sans-serif' }}>
        <Container style={{ margin: '0 auto', padding: '40px 20px', maxWidth: '560px' }}>
          <Heading style={{ fontSize: '24px', color: '#333' }}>
            Bienvenido, {userName}!
          </Heading>
          <Text style={{ fontSize: '16px', color: '#555', lineHeight: '1.6' }}>
            Su cuenta ha sido creada exitosamente. Inicie sesion desde el siguiente enlace para comenzar a usar el servicio.
          </Text>
          <Section style={{ textAlign: 'center', margin: '32px 0' }}>
            <Link
              href={loginUrl}
              style={{
                backgroundColor: '#2563eb',
                color: '#fff',
                padding: '12px 24px',
                borderRadius: '6px',
                textDecoration: 'none',
                fontSize: '16px',
              }}
            >
              Iniciar sesion
            </Link>
          </Section>
          <Text style={{ fontSize: '14px', color: '#888' }}>
            Si tiene alguna pregunta, no dude en contactarnos.
          </Text>
        </Container>
      </Body>
    </Html>
  );
}

Integracion del envio de correos

// src/services/notification-service.ts
import { render } from '@react-email/render';
import { EmailService } from './email-service';
import { WelcomeEmail } from '../emails/welcome';

const emailService = new EmailService();

export class NotificationService {
  async sendWelcomeEmail(user: { email: string; name: string }) {
    const html = await render(
      WelcomeEmail({
        userName: user.name,
        loginUrl: `${process.env.APP_URL}/login`,
      })
    );

    return emailService.send({
      to: user.email,
      subject: `Bienvenido, ${user.name}!`,
      html,
    });
  }

  async sendPasswordReset(email: string, token: string) {
    const resetUrl = `${process.env.APP_URL}/reset-password?token=${token}`;
    const html = await render(
      PasswordResetEmail({ resetUrl })
    );

    return emailService.send({
      to: email,
      subject: 'Instrucciones para restablecer su contrasena',
      html,
    });
  }
}

Implementacion de cola de correos

Para el envio masivo de correos se usan colas.

// src/queues/email-queue.ts
import { Queue, Worker } from 'bullmq';
import { EmailService } from '../services/email-service';

const emailQueue = new Queue('emails', {
  connection: { host: 'localhost', port: 6379 },
});

// Agregar correo a la cola
export async function enqueueEmail(options: {
  to: string;
  subject: string;
  html: string;
}) {
  await emailQueue.add('send-email', options, {
    attempts: 3,
    backoff: { type: 'exponential', delay: 2000 },
    removeOnComplete: 100,
    removeOnFail: 50,
  });
}

// Procesar con worker
const emailService = new EmailService();

new Worker('emails', async (job) => {
  await emailService.send(job.data);
  console.log(`Correo enviado: ${job.data.to}`);
}, {
  connection: { host: 'localhost', port: 6379 },
  concurrency: 5,
});

Implementacion de pruebas

import { vi, describe, it, expect } from 'vitest';
import { NotificationService } from './notification-service';

vi.mock('resend', () => ({
  Resend: vi.fn().mockImplementation(() => ({
    emails: {
      send: vi.fn().mockResolvedValue({ data: { id: 'test-id' }, error: null }),
    },
  })),
}));

describe('NotificationService', () => {
  it('should send welcome email', async () => {
    const service = new NotificationService();
    const result = await service.sendWelcomeEmail({
      email: '[email protected]',
      name: 'Usuario de prueba',
    });
    expect(result.id).toBe('test-id');
  });
});

Resumen

Con Claude Code, puede implementar la funcionalidad de envio de correos de manera integral, desde la gestion de plantillas hasta el procesamiento de colas. La creacion de plantillas con React Email es un area donde Claude Code destaca particularmente. Si describe las directrices de diseno de correo en CLAUDE.md, obtendra implementaciones consistentes. Para consejos sobre desarrollo dirigido por pruebas, consulte tambien el articulo sobre automatizacion de refactorizacion.

Para mas detalles sobre Claude Code, consulte la documentacion oficial de Anthropic. Para React Email, consulte el sitio oficial de React Email.

#Claude Code #email #SendGrid #Resend #Node.js