Cara Efficiently Implement Email Sending dengan Claude Code
Pelajari cara efficiently implement email sending menggunakan Claude Code. Dilengkapi contoh kode praktis dan panduan langkah demi langkah.
implementasiにClaude Codeを使うメリット メール機能
メールpengiriman機能 、template pembuatan、pengirimanロジック、errorハンドリング、リトライpemrosesan dll.考慮点 多い機能.Claude Code これら 一括 implementasiし、testdimungkinkanな構成 提案 くれ.
dasar Resendによるメールpengiriman
> Resend 使ったメールpengirimanservice buatkan.
> React Email dengan template manajemenして。
> リトライpemrosesan dan errorハンドリング implementasikan juga.
// 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); // 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でtemplatepembuatan
// 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>
);
}
integrasi メールpengiriman
// 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,
});
}
}
implementasi メールキュー
大量 メールpengiriman キュー 使い.
// 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 },
});
// メール キュー penambahan
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,
});
}
// ワーカー pemrosesan
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,
});
Implementasi Testing
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: 'testpengguna',
});
expect(result.id).toBe('test-id');
});
});
Summary
Dengan Claude Code, メールpengiriman機能 templatemanajemen dari キューpemrosesanま 一括 implementasi bisa dilakukan.特 React Email よるtemplatepembuatan 、Claude Code 得意 dan 分野.メール機能 設計方針 CLAUDE.md 記述 dan 、一貫 implementasi 得られ.test駆動 pengembangan 進めるコツ refactoringotomatisasi artikel juga bisa dijadikan referensi.
Untuk Claude Codeの詳細はAnthropic公式dokumenをご覧ください。React Emailの詳細, lihat React Email公式サイト.
Related Posts
Cara Mempercepat Side Project dengan Claude Code [Dengan Contoh]
Pelajari cara mempercepat project development personal secara drastis menggunakan Claude Code. Dilengkapi contoh nyata dan workflow praktis dari ide hingga deployment.
Cara Mengotomatisasi Refactoring dengan Claude Code
Pelajari cara mengotomatisasi code refactoring secara efisien menggunakan Claude Code. Dilengkapi prompt praktis dan pola refactoring konkret untuk project nyata.
Panduan Lengkap Konfigurasi CORS dengan Claude Code
Pelajari tentang panduan lengkap konfigurasi CORS menggunakan Claude Code. Dilengkapi tips praktis dan contoh kode.