如何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 <[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で模板创建
// 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: '[email protected]',
name: 'テストユーザー',
});
expect(result.id).toBe('test-id');
});
});
总结
借助 Claude Code,メール发送機能を模板管理から队列処理まで一括して实现可以。尤其React Email通过模板创建は、Claude Code 得意とする分野です。メール機能の设计方針をCLAUDE.mdに記述しておくと、一貫した实现が得られます。测试駆動で开发を進めるコツは重构自动化の文章也可以参考。
Claude Code 的详细信息请参阅Anthropic官方文档。React Email的详细信息请参阅React Email官方网站。
#Claude Code
#email
#SendGrid
#Resend
#Node.js
Related Posts
Use Cases
Use Cases
用 Claude Code 加速个人项目开发【附实战案例】
详解如何用 Claude Code 大幅提升个人项目的开发速度。包含从创意到上线的完整实战案例和工作流。
Use Cases
Use Cases
如何用 Claude Code 自动化代码重构
详解如何利用 Claude Code 高效完成代码重构自动化。包含实用提示词和真实项目中的重构模式。
Use Cases
Use Cases
Complete CORS Configuration Guide:Claude Code 实战指南
了解complete cors configuration guide:Claude Code 实战. 包含实用技巧和代码示例。