Email SendGrid avec Claude Code
Découvrez email SendGrid avec Claude Code. Conseils pratiques et exemples de code inclus.
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}`);
}
Summary
SendGridとClaude Codeを活用すれば、トランザクションメールからバルク配信まで効率的に実装できます。メール自動化ガイドやWebhook実装も合わせて参考にしてください。
SendGridの詳細はSendGrid公式ドキュメントを参照してください。
PDF gratuit : aide-mémoire Claude Code en 5 minutes
Laissez simplement votre e-mail et nous vous enverrons immédiatement l'aide-mémoire A4 en PDF.
Nous traitons vos données avec soin et n'envoyons jamais de spam.
À propos de l'auteur
Masa
Ingénieur passionné par Claude Code. Il gère claudecode-lab.com, un média tech en 10 langues avec plus de 2 000 pages.
Articles similaires
7 vérifications avant de publier chaque jour un article multilingue sur Claude Code
Une checklist pratique pour publier des articles multilingues sur Claude Code chaque jour sans oublier une langue, casser les CTA ou laisser l’ancien contenu en production.
Codex Automations : confier l'analyse, les articles et le deploiement a l'IA
Guide pratique pour utiliser Codex Automations dans une operation de contenu orientee monetisation.
Claude Code × GCP Cloud Functions Guide Complet | Développement Serverless Ultra-Rapide
Optimisez GCP Cloud Functions avec Claude Code. Implémentez des triggers HTTP/Pub/Sub/Firestore, des tests locaux et l'automatisation des déploiements avec des exemples de code réels de l'expérience de Masa.