Claude Code के साथ Implement SendGrid Email कैसे करें
Claude Code का उपयोग करके implement sendgrid email सीखें। Practical code examples और step-by-step guidance शामिल है।
SendGridメール送信को Claude Code सेefficientlyimplement करना
SendGridはTwilioが提供するクラウドメール配信service है।高い到達率とスケーラブルな配信基盤を備え、トランザクションメール सेマーケティングメール तक幅広くsupportし है।Claude Code का उपयोग करके、メール送信featuresをefficientlybuild करें।
basic メール送信
> SendGridでメール送信するserviceclassを作って。
> templatesupportとerror handlingも含めて。
// 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は1requestで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;
}
}
ダイナミックtemplateのutilization
> ウェルカムメールとpathワードリセットメールの
> templateを使った送信processingをimplement करो。
// src/services/transactional-emails.ts
import { EmailService } from './email';
const emailService = new EmailService();
// templateIDの定数management
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: 'pathワードリセットのご案内',
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: `ご注文confirm #${order.id}`,
templateId: TEMPLATES.ORDER_CONFIRMATION,
dynamicData: {
orderId: order.id,
items: order.items,
total: order.total.toLocaleString('en-US'),
},
});
}
Webhook でeventprocessing
> SendGridのEvent Webhookをprocessingして、
> バウンスやスパム報告を記録するendpointを作って。
// 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) {
// バウンスしたアドレスを送信停止listにadd
console.log(`Bounce: ${email} - ${reason}`);
}
async function handleSpamReport(email: string) {
// スパム報告があったアドレスを除बाहर
console.log(`Spam report: ${email}`);
}
async function handleUnsubscribe(email: string) {
// 配信停止processing
console.log(`Unsubscribed: ${email}`);
}
async function logDelivery(email: string, messageId: string) {
console.log(`Delivered to ${email}: ${messageId}`);
}
Summary
SendGridとClaude Code का लाभ उठाकर、トランザクションメール सेバルク配信 तकefficientlyimplementationでき है।メールautomationガイドやWebhookimplementationも合わせてreference के लिए देखें。
SendGridके details के लिएSendGridofficial documentationをदेखें。
Related Posts
Claude Code से अपने Side Projects को Supercharge कैसे करें [Examples के साथ]
Claude Code से personal development projects को dramatically speed up करना सीखें। Real-world examples और idea से deployment तक practical workflow शामिल है।
Claude Code से Refactoring कैसे Automate करें
Claude Code से efficiently code refactoring automate करना सीखें। Real-world projects के लिए practical prompts और concrete refactoring patterns शामिल हैं।
Claude Code के साथ Complete CORS Configuration Guide
Claude Code का उपयोग करके complete CORS configuration guide सीखें। Practical tips और code examples शामिल हैं।