如何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
免费
免费 PDF:5 分钟看懂 Claude Code 速查表
只需留下邮箱,我们就会立即把这份 A4 一页速查表 PDF 发送给你。
我们会严格保护你的个人信息,绝不发送垃圾邮件。
把 Claude Code 变成真正能带来结果的工作流
先领取中文说明的免费 PDF,再进入英文商品页选择合适的教材。如果你需要团队落地、流程设计或内容变现支持,也可以直接咨询。
本文作者
Masa
深度使用 Claude Code 的工程师。运营 claudecode-lab.com——一个涵盖 10 种语言、超过 2,000 页内容的科技媒体。
相关文章
Use Cases
每天发布多语言 Claude Code 文章前,要先检查的 7 件事
一份实用清单,帮助你每天发布多语言 Claude Code 文章时避免漏语言、CTA 错位和线上内容未更新。
Use Cases
Codex Automations 是什么?让 AI 在你睡觉时完成内容运营
用 Codex Automations 自动查看流量、选择主题、写文章、改善转化路径并部署网站的实用指南。
Use Cases
Claude Code × GCP Cloud Functions 完全指南 | 极速开发无服务器函数
用 Claude Code 高效开发 GCP Cloud Functions。从 HTTP/Pub/Sub/Firestore 触发器实现到本地测试、部署自动化,基于 Masa 的实战经验,附完整可运行代码示例。