Como Implementar E-mail SendGrid com Claude Code
Aprenda a implement sendgrid email usando o Claude Code. Inclui exemplos praticos de codigo e orientacao passo a passo.
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 gratuito: Cheatsheet do Claude Code em 5 minutos
Basta informar seu e-mail e enviamos na hora o cheatsheet em uma página A4.
Cuidamos dos seus dados pessoais e nunca enviamos spam.
Sobre o autor
Masa
Engenheiro apaixonado por Claude Code. Mantém o claudecode-lab.com, uma mídia tech em 10 idiomas com mais de 2.000 páginas.
Artigos relacionados
7 verificações antes de publicar todos os dias um artigo multilíngue sobre Claude Code
Uma checklist prática para publicar artigos multilíngues sobre Claude Code todos os dias sem esquecer idiomas, quebrar CTAs ou deixar páginas antigas no ar.
O que e Codex Automations? Conteudo, analise e deploy com IA enquanto voce dorme
Guia pratico para usar Codex Automations em analytics, artigos, CTA, deploy e monetizacao.
Desenhe Firestore com Claude Code: comece pelas consultas
Workflow prático para Firestore com Claude Code: schema orientado por consultas, índices, custos, regras de segurança e TypeScript.