Use Cases

如何Implement SendGrid Email:Claude Code 实战指南

学习如何implement sendgrid email:Claude Code 实战. 包含实用代码示例和分步指导。

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}`);
}

总结

SendGridとClaude Codeを活用すれば、事务メールからバルク配信まで高效地实现可以。メール自动化指南Webhook实现也建议一并参考。

SendGrid的详细信息请参阅SendGrid官方文档

#Claude Code #SendGrid #email #API #automation