How to Implement SendGrid Email with Claude Code
Learn how to implement sendgrid email using Claude Code. Includes practical code examples and step-by-step guidance.
SendGridメール送信をClaude Codeで効率的に実装する
SendGridはTwilioが提供するクラウドメール配信サービスです。高い到達率とスケーラブルな配信基盤を備え、トランザクションメールからマーケティングメールまで幅広く対応します。Claude Codeを活用して、メール送信機能を効率的に構築しましょう。
基本的なメール送信
> SendGridでメール送信するサービスクラスを作って。
> テンプレート対応とエラーハンドリングも含めて。
// src/services/email.ts
import sgMail from '@sendgrid/mail';
sgMail.setApiKey(process.env.SENDGRID_API_KEY!);
interface EmailOptions {
to: string | string[];
subject: string;
text?: string;
html?: string;
templateId?: string;
dynamicData?: Record<string, unknown>;
}
export class EmailService {
private from = {
email: '[email protected]',
name: 'MyApp',
};
async send(options: EmailOptions): Promise<void> {
const msg: sgMail.MailDataRequired = {
to: options.to,
from: this.from,
subject: options.subject,
};
if (options.templateId) {
msg.templateId = options.templateId;
msg.dynamicTemplateData = options.dynamicData;
} else {
msg.text = options.text || '';
msg.html = options.html || '';
}
try {
await sgMail.send(msg);
console.log(`Email sent to ${options.to}`);
} catch (error: any) {
if (error.response) {
console.error('SendGrid error:', error.response.body);
}
throw new Error(`Failed to send email: ${error.message}`);
}
}
async sendBulk(
recipients: { email: string; data: Record<string, unknown> }[],
templateId: string
): Promise<void> {
const messages = recipients.map((r) => ({
to: r.email,
from: this.from,
templateId,
dynamicTemplateData: r.data,
}));
// SendGridは1リクエストで1000通まで
const chunks = this.chunk(messages, 1000);
for (const chunk of chunks) {
await sgMail.send(chunk);
}
}
private chunk<T>(array: T[], size: number): T[][] {
const chunks: T[][] = [];
for (let i = 0; i < array.length; i += size) {
chunks.push(array.slice(i, i + size));
}
return chunks;
}
}
ダイナミックテンプレートの活用
> ウェルカムメールとパスワードリセットメールの
> テンプレートを使った送信処理を実装して。
// src/services/transactional-emails.ts
import { EmailService } from './email';
const emailService = new EmailService();
// テンプレートIDの定数管理
const TEMPLATES = {
WELCOME: 'd-xxxxxxxxxxxxxxxxxxxx',
PASSWORD_RESET: 'd-yyyyyyyyyyyyyyyyyyyy',
ORDER_CONFIRMATION: 'd-zzzzzzzzzzzzzzzzzzzz',
} as const;
export async function sendWelcomeEmail(
email: string,
name: string
) {
await emailService.send({
to: email,
subject: 'ようこそ!',
templateId: TEMPLATES.WELCOME,
dynamicData: {
name,
loginUrl: `${process.env.APP_URL}/login`,
supportEmail: '[email protected]',
},
});
}
export async function sendPasswordResetEmail(
email: string,
resetToken: string
) {
const resetUrl = `${process.env.APP_URL}/reset-password?token=${resetToken}`;
await emailService.send({
to: email,
subject: 'パスワードリセットのご案内',
templateId: TEMPLATES.PASSWORD_RESET,
dynamicData: {
resetUrl,
expiresIn: '24時間',
},
});
}
export async function sendOrderConfirmation(
email: string,
order: { id: string; items: any[]; total: number }
) {
await emailService.send({
to: email,
subject: `ご注文確認 #${order.id}`,
templateId: TEMPLATES.ORDER_CONFIRMATION,
dynamicData: {
orderId: order.id,
items: order.items,
total: order.total.toLocaleString('en-US'),
},
});
}
Webhook でイベント処理
> SendGridのEvent Webhookを処理して、
> バウンスやスパム報告を記録するエンドポイントを作って。
// src/api/sendgrid-webhook.ts
interface SendGridEvent {
email: string;
event: string;
timestamp: number;
reason?: string;
sg_message_id?: string;
}
export async function handleSendGridWebhook(events: SendGridEvent[]) {
for (const event of events) {
switch (event.event) {
case 'bounce':
await handleBounce(event.email, event.reason || '');
break;
case 'spamreport':
await handleSpamReport(event.email);
break;
case 'unsubscribe':
await handleUnsubscribe(event.email);
break;
case 'delivered':
await logDelivery(event.email, event.sg_message_id || '');
break;
}
}
}
async function handleBounce(email: string, reason: string) {
// バウンスしたアドレスを送信停止リストに追加
console.log(`Bounce: ${email} - ${reason}`);
}
async function handleSpamReport(email: string) {
// スパム報告があったアドレスを除外
console.log(`Spam report: ${email}`);
}
async function handleUnsubscribe(email: string) {
// 配信停止処理
console.log(`Unsubscribed: ${email}`);
}
async function logDelivery(email: string, messageId: string) {
console.log(`Delivered to ${email}: ${messageId}`);
}
Zusammenfassung
SendGridとClaude Codeを活用すれば、トランザクションメールからバルク配信まで効率的に実装できます。メール自動化ガイドやWebhook実装も合わせて参考にしてください。
SendGridの詳細はSendGrid公式ドキュメントを参照してください。
Related Posts
So beschleunigen Sie Ihre Nebenprojekte mit Claude Code [Mit Beispielen]
Erfahren Sie, wie Sie persönliche Entwicklungsprojekte mit Claude Code drastisch beschleunigen. Inklusive realer Beispiele und eines praktischen Workflows von der Idee bis zum Deployment.
So automatisieren Sie Refactoring mit Claude Code
Erfahren Sie, wie Sie Code-Refactoring mit Claude Code effizient automatisieren. Inklusive praktischer Prompts und konkreter Refactoring-Muster für reale Projekte.
Vollständiger CORS-Konfigurationsleitfaden mit Claude Code
Erfahren Sie alles über die CORS-Konfiguration mit Claude Code. Mit praktischen Tipps und Codebeispielen.