EmailVerify LogoEmailVerify

TypeScript

TypeScript email checker SDK with full type definitions. Type-safe email verification for Node.js.

EmailVerify TypeScript SDK は、TypeScript プロジェクトでの型安全なメール検証のための完全な型定義を提供します。

TypeScript SDK は Node.js SDK と同じパッケージを共有していますが、完全な TypeScript サポートを備えています。

インストール

npm install @emailverify/node
# または
yarn add @emailverify/node
# または
pnpm add @emailverify/node

クイックスタート

import { EmailVerify, VerificationResult } from '@emailverify/node';

const client = new EmailVerify({
  apiKey: process.env.EMAILVERIFY_API_KEY!,
});

const result: VerificationResult = await client.verify('user@example.com');
console.log(result.status); // 型: 'valid' | 'invalid' | 'unknown' | 'accept_all'

型定義

クライアントオプション

interface ClientOptions {
  apiKey: string;
  timeout?: number;           // デフォルト: 30000ms
  retries?: number;           // デフォルト: 3
  retryDelay?: number;        // デフォルト: 1000ms
  retryMaxDelay?: number;     // デフォルト: 30000ms
  baseUrl?: string;           // デフォルト: 'https://api.emailverify.ai'
}

検証結果

interface VerificationResult {
  email: string;
  status: VerificationStatus;
  result: ResultDetails;
  score: number;
  reason: string | null;
}

type VerificationStatus = 'valid' | 'invalid' | 'unknown' | 'accept_all';

interface ResultDetails {
  deliverable: boolean | null;
  valid_format: boolean;
  valid_domain: boolean;
  valid_mx: boolean;
  disposable: boolean;
  role: boolean;
  catchall: boolean;
  free: boolean;
  smtp_valid: boolean | null;
}

一括ジョブタイプ

interface BulkJob {
  id: string;
  status: BulkJobStatus;
  total: number;
  processed: number;
  valid: number;
  invalid: number;
  unknown: number;
  created_at: string;
  completed_at: string | null;
}

type BulkJobStatus = 'pending' | 'processing' | 'completed' | 'failed';

interface BulkJobResults {
  job_id: string;
  results: VerificationResult[];
}

エラータイプ

class EmailVerifyError extends Error {
  code: string;
  statusCode?: number;
}

class AuthenticationError extends EmailVerifyError {
  code: 'authentication_error';
}

class RateLimitError extends EmailVerifyError {
  code: 'rate_limit_error';
  retryAfter: number;
}

class ValidationError extends EmailVerifyError {
  code: 'validation_error';
  field?: string;
}

設定

const client = new EmailVerify({
  apiKey: process.env.EMAILVERIFY_API_KEY!,
  timeout: 30000,
  retries: 3,
});

単一検証

基本的な使用方法

const result = await client.verify('user@example.com');

// TypeScript はすべてのプロパティとその型を認識します
if (result.status === 'valid') {
  console.log(`Score: ${result.score}`);
  console.log(`Deliverable: ${result.result.deliverable}`);
}

オプション付き

interface VerifyOptions {
  smtpCheck?: boolean;
  timeout?: number;
}

const result = await client.verify('user@example.com', {
  smtpCheck: true,
  timeout: 5000,
});

型ガード

function isValidEmail(result: VerificationResult): boolean {
  return result.status === 'valid' && result.score >= 0.8;
}

function isSafeForMarketing(result: VerificationResult): boolean {
  return (
    result.status === 'valid' &&
    !result.result.disposable &&
    !result.result.role
  );
}

一括検証

ジョブの送信

const emails: string[] = [
  'user1@example.com',
  'user2@example.com',
];

const job: BulkJob = await client.verifyBulk(emails);

ステータスの取得

const status: BulkJob = await client.getBulkJobStatus(job.id);

// 型安全なステータスチェック
switch (status.status) {
  case 'pending':
    console.log('ジョブはキューに入っています');
    break;
  case 'processing':
    console.log(`進捗: ${status.processed}/${status.total}`);
    break;
  case 'completed':
    console.log(`完了!有効: ${status.valid}, 無効: ${status.invalid}`);
    break;
  case 'failed':
    console.log('ジョブが失敗しました');
    break;
}

結果の取得

const results: BulkJobResults = await client.getBulkJobResults(job.id);

results.results.forEach((result) => {
  console.log(`${result.email}: ${result.status}`);
});

エラーハンドリング

import {
  EmailVerify,
  EmailVerifyError,
  AuthenticationError,
  RateLimitError,
  ValidationError,
} from '@emailverify/node';

async function verifyEmail(email: string): Promise<VerificationResult | null> {
  try {
    return await client.verify(email);
  } catch (error) {
    if (error instanceof AuthenticationError) {
      console.error('API キーが無効です');
    } else if (error instanceof RateLimitError) {
      console.error(`レート制限に達しました。${error.retryAfter} 秒後にリトライしてください`);
    } else if (error instanceof ValidationError) {
      console.error(`入力が無効です: ${error.message}`);
    } else if (error instanceof EmailVerifyError) {
      console.error(`API エラー: ${error.message}`);
    }
    return null;
  }
}

汎用ユーティリティ

型安全な検証関数

type ValidationResult =
  | { valid: true; score: number }
  | { valid: false; reason: string; message: string };

async function validateEmail(email: string): Promise<ValidationResult> {
  const result = await client.verify(email);

  if (result.status === 'invalid') {
    return {
      valid: false,
      reason: 'invalid_email',
      message: 'このメールアドレスは無効です',
    };
  }

  if (result.result.disposable) {
    return {
      valid: false,
      reason: 'disposable',
      message: '使い捨てメールは許可されていません',
    };
  }

  return {
    valid: true,
    score: result.score,
  };
}

カスタム結果処理

interface ProcessedResult {
  email: string;
  isValid: boolean;
  riskLevel: 'low' | 'medium' | 'high';
  flags: string[];
}

function processResult(result: VerificationResult): ProcessedResult {
  const flags: string[] = [];

  if (result.result.disposable) flags.push('disposable');
  if (result.result.role) flags.push('role');
  if (result.result.catchall) flags.push('catchall');
  if (result.result.free) flags.push('free');

  let riskLevel: 'low' | 'medium' | 'high';
  if (result.score >= 0.8) {
    riskLevel = 'low';
  } else if (result.score >= 0.5) {
    riskLevel = 'medium';
  } else {
    riskLevel = 'high';
  }

  return {
    email: result.email,
    isValid: result.status === 'valid',
    riskLevel,
    flags,
  };
}

フレームワーク統合

Next.js App Router

// app/api/verify/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { EmailVerify, VerificationResult } from '@emailverify/node';

const client = new EmailVerify({
  apiKey: process.env.EMAILVERIFY_API_KEY!,
});

interface RequestBody {
  email: string;
}

interface ResponseBody {
  valid: boolean;
  score?: number;
  message?: string;
}

export async function POST(request: NextRequest): Promise<NextResponse<ResponseBody>> {
  const body: RequestBody = await request.json();

  try {
    const result: VerificationResult = await client.verify(body.email);

    if (result.status === 'invalid') {
      return NextResponse.json(
        { valid: false, message: '無効なメールアドレスです' },
        { status: 400 }
      );
    }

    return NextResponse.json({
      valid: true,
      score: result.score,
    });
  } catch (error) {
    return NextResponse.json(
      { valid: false, message: '検証に失敗しました' },
      { status: 500 }
    );
  }
}

NestJS サービス

// email-verification.service.ts
import { Injectable } from '@nestjs/common';
import { EmailVerify, VerificationResult } from '@emailverify/node';

@Injectable()
export class EmailVerificationService {
  private client: EmailVerify;

  constructor() {
    this.client = new EmailVerify({
      apiKey: process.env.EMAILVERIFY_API_KEY!,
    });
  }

  async verify(email: string): Promise<VerificationResult> {
    return this.client.verify(email);
  }

  async isValidForRegistration(email: string): Promise<boolean> {
    const result = await this.verify(email);
    return (
      result.status === 'valid' &&
      !result.result.disposable &&
      result.score >= 0.7
    );
  }
}

Express with TypeScript

import express, { Request, Response } from 'express';
import { EmailVerify, VerificationResult } from '@emailverify/node';

const app = express();
app.use(express.json());

const client = new EmailVerify({
  apiKey: process.env.EMAILVERIFY_API_KEY!,
});

interface VerifyRequest {
  email: string;
}

interface VerifyResponse {
  success: boolean;
  data?: VerificationResult;
  error?: string;
}

app.post('/verify', async (
  req: Request<{}, VerifyResponse, VerifyRequest>,
  res: Response<VerifyResponse>
) => {
  try {
    const result = await client.verify(req.body.email);
    res.json({ success: true, data: result });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error instanceof Error ? error.message : '不明なエラー',
    });
  }
});

Zod スキーマ統合

import { z } from 'zod';
import { EmailVerify } from '@emailverify/node';

const client = new EmailVerify({
  apiKey: process.env.EMAILVERIFY_API_KEY!,
});

const emailSchema = z.string().email().refine(
  async (email) => {
    try {
      const result = await client.verify(email);
      return result.status === 'valid';
    } catch {
      return false;
    }
  },
  { message: 'メールアドレスが有効でないか、配信できません' }
);

// 使用例
async function validateEmail(email: string) {
  return emailSchema.parseAsync(email);
}

ベストプラクティス

1. Strict Null Checks を使用

// tsconfig.json
{
  "compilerOptions": {
    "strict": true,
    "strictNullChecks": true
  }
}

// 適切な null ハンドリングを行うコード
const result = await client.verify(email);
if (result.result.deliverable !== null) {
  console.log(`Deliverable: ${result.result.deliverable}`);
}

2. 型安全なラッパーを作成

// verification.ts
export async function verifyAndCategorize(email: string) {
  const result = await client.verify(email);

  return {
    email: result.email,
    category: categorize(result),
    score: result.score,
    details: result.result,
  } as const;
}

function categorize(result: VerificationResult) {
  if (result.status !== 'valid') return 'invalid';
  if (result.result.disposable) return 'disposable';
  if (result.result.role) return 'role';
  return 'valid';
}

次のステップ

On this page