# Send Bulk SMS with CSV Streaming & Batch Progress
URL: /docs/recipes/send-bulk-sms-campaign

> Ingest high-volume CSV contact lists without memory leaks, dispatch chunked batch jobs, and poll asynchronous campaign completion.

Difficulty: Intermediate | Duration: 9 min | Language: TypeScript

## Step 1: 1. Configure Dependencies & Environment (`Terminal`)

Install `csv-parser` to handle Node.js streaming ingestion with minimal memory overhead.

```bash
npm install csv-parser dotenv
```

## Step 2: 2. Build the Streaming CSV Recipient Parser (`src/stream-contacts.ts`)

Read the CSV file as an asynchronous stream. Clean and normalize each phone number to standard format, discarding duplicates and malformed records on the fly.

```ts
import fs from 'node:fs';
import csv from 'csv-parser';

export interface CsvContact {
  phone: string;
  name: string;
}

/**
 * Streams contacts from CSV without loading the entire file into memory.
 */
export async function* streamContacts(filePath: string): AsyncGenerator<CsvContact> {
  const stream = fs.createReadStream(filePath).pipe(csv());
  const seenPhones = new Set<string>();

  for await (const row of stream) {
    const rawPhone = row.phone || row.mobile || row.phoneNumber;
    if (!rawPhone) continue;

    // Normalize: strip non-digits; if starting with 0, prepend 233
    const digits = String(rawPhone).replace(/\D/g, '');
    let normalized = digits;
    if (digits.startsWith('0') && digits.length === 10) {
      normalized = `233${digits.substring(1)}`;
    }

    if (normalized.length >= 9 && !seenPhones.has(normalized)) {
      seenPhones.add(normalized);
      yield {
        phone: normalized,
        name: row.name || 'Valued Customer',
      };
    }
  }
}
```

## Step 3: 3. Dispatch Chunked Asynchronous Batch Jobs (`src/dispatch-campaign.ts`)

Accumulate recipients into chunks of 1,000 recipients and submit each chunk to `POST /api/v1/public/sms/batch`. Attach a unique `Idempotency-Key` to each batch chunk.

```ts
import crypto from 'node:crypto';
import { streamContacts, CsvContact } from './stream-contacts';
import { pollJobProgress } from './poll-progress';

const BASE_URL = process.env.SMSPRO_BASE_URL || 'https://api.smspro.com';
const API_KEY = process.env.SMSPRO_API_KEY!;
const BATCH_SIZE = 1000;

interface BatchSubmissionResponse {
  status: string;
  data: {
    jobId: string;
    totalRecipients: number;
    status: string;
  };
}

export async function runCampaign(csvPath: string, messageTemplate: string) {
  let batchBuffer: CsvContact[] = [];
  const submittedJobIds: string[] = [];

  console.log(`🚀 Starting campaign ingestion from ${csvPath}...`);

  for await (const contact of streamContacts(csvPath)) {
    batchBuffer.push(contact);

    if (batchBuffer.length >= BATCH_SIZE) {
      const jobId = await submitBatchChunk(batchBuffer, messageTemplate);
      submittedJobIds.push(jobId);
      batchBuffer = [];
    }
  }

  // Flush remaining contacts
  if (batchBuffer.length > 0) {
    const jobId = await submitBatchChunk(batchBuffer, messageTemplate);
    submittedJobIds.push(jobId);
  }

  console.log(`✅ All batches submitted! Monitoring ${submittedJobIds.length} background jobs...`);
  
  for (const jobId of submittedJobIds) {
    await pollJobProgress(jobId);
  }

  console.log('🎉 Campaign processing completed successfully!');
}

async function submitBatchChunk(contacts: CsvContact[], template: string): Promise<string> {
  const idempotencyKey = crypto.randomUUID();
  
  const payload = {
    senderId: 'SMSPRO',
    messages: contacts.map((c) => ({
      to: c.phone,
      message: template.replace('{{name}}', c.name),
    })),
  };

  const res = await fetch(`${BASE_URL}/api/v1/public/sms/batch`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Api-Key': API_KEY,
      'Idempotency-Key': idempotencyKey,
    },
    body: JSON.stringify(payload),
  });

  if (!res.ok) {
    const errorBody = await res.text();
    throw new Error(`Batch submission failed [${res.status}]: ${errorBody}`);
  }

  const json: BatchSubmissionResponse = await res.json();
  console.log(`📦 Enqueued Batch [${json.data.jobId}] with ${contacts.length} recipients`);
  return json.data.jobId;
}
```

## Step 4: 4. Poll Campaign Progress & Completion (`src/poll-progress.ts`)

Periodically query `GET /api/v1/public/sms/batch/{jobId}/progress` until the job reaches a terminal state (`COMPLETED` or `FAILED`).

```ts
const BASE_URL = process.env.SMSPRO_BASE_URL || 'https://api.smspro.com';
const API_KEY = process.env.SMSPRO_API_KEY!;

interface JobProgressResponse {
  status: string;
  data: {
    jobId: string;
    total: number;
    processed: number;
    successful: number;
    failed: number;
    status: 'QUEUED' | 'PROCESSING' | 'COMPLETED' | 'FAILED';
  };
}

export async function pollJobProgress(jobId: string, intervalMs = 2500): Promise<void> {
  while (true) {
    const res = await fetch(`${BASE_URL}/api/v1/public/sms/batch/${jobId}/progress`, {
      headers: { 'X-Api-Key': API_KEY },
    });

    if (!res.ok) {
      console.warn(`Failed to poll progress for ${jobId} [${res.status}]`);
      await sleep(intervalMs);
      continue;
    }

    const { data }: JobProgressResponse = await res.json();
    const percent = data.total > 0 ? Math.round((data.processed / data.total) * 100) : 0;
    
    console.log(`📊 Job ${jobId}: ${percent}% (${data.processed}/${data.total}) | Success: ${data.successful} | Failed: ${data.failed}`);

    if (data.status === 'COMPLETED' || data.status === 'FAILED') {
      console.log(`🏁 Job ${jobId} finished with status: ${data.status}`);
      break;
    }

    await sleep(intervalMs);
  }
}

function sleep(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
```