How to Efficiently Implement Email Sending: Claude Code 활용 가이드
efficiently implement email sending: Claude Code 활용. 실용적인 코드 예시와 단계별 가이드를 포함합니다.
メール機能の구현にClaude Code를 사용하는メリット
メール전송機能は、템플릿の생성、전송ロジック、에러 핸들링、リトライ処理など考慮点が多い機能です。Claude Code는 이것らを一括して구현し、테스트可能な구성を提案してくれます。
Resend에 의한メール전송の基本
> Resend를 사용한メール전송サービス를 생성해줘。
> React Emailで템플릿を관리して。
> リトライ処理と에러 핸들링も구현して。
// 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 <noreply@example.com>',
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); // Exponential backoff
}
}
}
throw new Error(`Failed after ${this.maxRetries} attempts: ${lastError?.message}`);
}
private delay(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
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>{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' }}>
ようこそ、{userName}さん!
</Heading>
<Text style={{ fontSize: '16px', color: '#555', lineHeight: '1.6' }}>
アカウントが正常に作成されました。以下のリンクからログインしてサービスをご利用ください。
</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',
}}
>
ログインする
</Link>
</Section>
<Text style={{ fontSize: '14px', color: '#888' }}>
ご不明な点がございましたらお気軽にお問い合わせください。
</Text>
</Container>
</Body>
</Html>
);
}
メール전송の통합
// 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: `ようこそ、${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: 'パスワードリセットのご案内',
html,
});
}
}
メール큐の구현
大量のメール전송には큐를 사용합니다。
// 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 },
});
// メールを큐に추가
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,
});
}
// ワーカーで処理
const emailService = new EmailService();
new Worker('emails', async (job) => {
await emailService.send(job.data);
console.log(`Email sent: ${job.data.to}`);
}, {
connection: { host: 'localhost', port: 6379 },
concurrency: 5,
});
테스트の구현
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: 'test@example.com',
name: 'テストユーザー',
});
expect(result.id).toBe('test-id');
});
});
정리
Claude Code를 활용하면 メール전송機能を템플릿관리から큐処理まで一括して구현할 수 있습니다。특히React Email에 의한템플릿생성は、Claude Code가 得意とする分野です。メール機能の설계方針をCLAUDE.mdに記述しておくと、一貫した구현が得られます。테스트駆動で개발を進めるコツは리팩터링자동화の글도 참고하세요.
Claude Code의 상세 정보는Anthropic공식 문서를 확인하세요.React Email의 상세 정보는React Email공식 사이트를 참고하세요.
Claude Code 워크플로우를 한 단계 업그레이드하세요
지금 바로 Claude Code에 복사해 쓸 수 있는 검증된 프롬프트 템플릿 50선.
이 글을 작성한 사람
Masa
Claude Code를 적극 활용하는 엔지니어. 10개 언어, 2,000페이지 이상의 테크 미디어 claudecode-lab.com을 운영 중.
관련 글
Claude Code로 리팩토링을 자동화하는 방법
Claude Code를 활용해 코드 리팩토링을 효율적으로 자동화하는 방법을 알아봅니다. 실전 프롬프트와 구체적인 리팩토링 패턴을 소개합니다.
Claude Code로 사이드 프로젝트 개발 속도를 극대화하는 방법 [예제 포함]
Claude Code를 활용해 개인 프로젝트 개발 속도를 획기적으로 높이는 방법을 알아봅니다. 실전 예제와 아이디어부터 배포까지의 워크플로를 포함합니다.
Complete CORS Configuration Guide: Claude Code 활용 가이드
complete cors configuration guide: Claude Code 활용. 실용적인 팁과 코드 예시를 포함합니다.