Codex
Email checker with OpenAI Codex CLI. Verify emails in Codex automation.
OpenAI Codex CLIはAI搭載のコード生成とターミナル支援を提供します。EmailVerifyをメール検証タスクに統合する方法を学びます。
Codex CLIとは?
Codex CLIはOpenAIのコマンドラインツールで、Codexモデルを活用します:
- 自然言語からコードへの変換
- シェルコマンド生成
- コード補完とデバッグ
- タスク自動化
セットアップ
EmailVerify CLIのインストール
npm install -g @emailverify/cli
bv config set api-key YOUR_API_KEY環境設定
export EMAILVERIFY_API_KEY=your-api-key
export OPENAI_API_KEY=your-openai-key使用例
検証スクリプトの生成
プロンプト: EmailVerify APIを使用してメールリストを検証するPythonスクリプトを書いて
Codex出力:
import os
import requests
from typing import List, Dict
def verify_emails(emails: List[str]) -> List[Dict]:
"""Verify a list of email addresses using EmailVerify API."""
api_key = os.environ.get('EMAILVERIFY_API_KEY')
results = []
for email in emails:
response = requests.post(
'https://api.emailverify.ai/v1/verify',
headers={
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json',
},
json={'email': email}
)
results.append(response.json())
return results
def main():
emails = [
'test@example.com',
'user@gmail.com',
'fake@mailinator.com',
]
results = verify_emails(emails)
for result in results:
status = 'OK' if result['status'] == 'valid' else 'NG'
print(f"{status} {result['email']}: {result['status']}")
if __name__ == '__main__':
main()シェルコマンドの生成
プロンプト: CSVファイルの2列目のすべてのメールを検証するワンライナー
Codex出力:
cut -d',' -f2 users.csv | tail -n +2 | while read email; do bv verify "$email" --quiet && echo "OK $email" || echo "NG $email"; doneテストケースの生成
プロンプト: メール検証関数用のJestテストを生成して
Codex出力:
import { verifyEmail } from './email-service';
describe('Email Verification', () => {
beforeAll(() => {
process.env.EMAILVERIFY_API_KEY = 'test-api-key';
});
test('validates correct email format', async () => {
const result = await verifyEmail('user@example.com');
expect(result).toHaveProperty('status');
expect(result).toHaveProperty('score');
});
test('rejects invalid email format', async () => {
const result = await verifyEmail('not-an-email');
expect(result.status).toBe('invalid');
});
test('detects disposable emails', async () => {
const result = await verifyEmail('test@mailinator.com');
expect(result.result.disposable).toBe(true);
});
test('handles API errors gracefully', async () => {
// Simulate network error
const result = await verifyEmail('test@example.com');
expect(result).not.toBeNull();
});
});API統合の生成
プロンプト: キャッシュ機能付きのEmailVerify統合用Node.jsモジュールを作成して
Codex出力:
import NodeCache from 'node-cache';
interface VerificationResult {
email: string;
status: 'valid' | 'invalid' | 'unknown';
score: number;
result: {
deliverable: boolean;
disposable: boolean;
role: boolean;
};
}
class EmailVerifyClient {
private apiKey: string;
private cache: NodeCache;
private baseUrl = 'https://api.emailverify.ai/v1';
constructor(apiKey: string, cacheTTL: number = 3600) {
this.apiKey = apiKey;
this.cache = new NodeCache({ stdTTL: cacheTTL });
}
async verify(email: string): Promise<VerificationResult> {
// Check cache first
const cached = this.cache.get<VerificationResult>(email);
if (cached) return cached;
const response = await fetch(`${this.baseUrl}/verify`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ email }),
});
const result = await response.json();
// Cache the result
this.cache.set(email, result);
return result;
}
async verifyBulk(emails: string[]): Promise<VerificationResult[]> {
const response = await fetch(`${this.baseUrl}/verify/bulk`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ emails }),
});
return response.json();
}
}
export default EmailVerifyClient;コード生成パターン
パターン1: バリデーションミドルウェア
プロンプト: リクエストボディのメールを検証するExpressミドルウェア
import { Request, Response, NextFunction } from 'express';
export const validateEmail = async (
req: Request,
res: Response,
next: NextFunction
) => {
const { email } = req.body;
if (!email) {
return res.status(400).json({ error: 'Email is required' });
}
const response = await fetch('https://api.emailverify.ai/v1/verify', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.EMAILVERIFY_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ email }),
});
const result = await response.json();
if (result.status === 'invalid') {
return res.status(400).json({ error: 'Invalid email address' });
}
if (result.result.disposable) {
return res.status(400).json({ error: 'Disposable emails not allowed' });
}
req.verificationResult = result;
next();
};パターン2: Reactフック
プロンプト: デバウンス付きのメール検証Reactフック
import { useState, useEffect } from 'react';
import { useDebouncedCallback } from 'use-debounce';
interface VerificationState {
isLoading: boolean;
isValid: boolean | null;
result: any;
error: string | null;
}
export function useEmailVerification(debounceMs: number = 500) {
const [state, setState] = useState<VerificationState>({
isLoading: false,
isValid: null,
result: null,
error: null,
});
const verify = useDebouncedCallback(async (email: string) => {
if (!email || !email.includes('@')) {
setState({ isLoading: false, isValid: null, result: null, error: null });
return;
}
setState(prev => ({ ...prev, isLoading: true, error: null }));
try {
const response = await fetch('/api/verify-email', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email }),
});
const result = await response.json();
setState({
isLoading: false,
isValid: result.status === 'valid',
result,
error: null,
});
} catch (error) {
setState({
isLoading: false,
isValid: null,
result: null,
error: 'Verification failed',
});
}
}, debounceMs);
return { ...state, verify };
}