惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Threat Research - Cisco Blogs
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
The Register - Security
The Register - Security
A
About on SuperTechFans
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
L
LangChain Blog
N
Netflix TechBlog - Medium
量子位
博客园 - 三生石上(FineUI控件)
宝玉的分享
宝玉的分享
H
Help Net Security
D
Docker
D
DataBreaches.Net
T
Tailwind CSS Blog
阮一峰的网络日志
阮一峰的网络日志
B
Blog
博客园 - 聂微东
Apple Machine Learning Research
Apple Machine Learning Research
Google DeepMind News
Google DeepMind News
The Cloudflare Blog
F
Full Disclosure
GbyAI
GbyAI
F
Fortinet All Blogs
Last Week in AI
Last Week in AI
Y
Y Combinator Blog
人人都是产品经理
人人都是产品经理
Recent Announcements
Recent Announcements
博客园 - Franky
MongoDB | Blog
MongoDB | Blog
有赞技术团队
有赞技术团队
博客园 - 叶小钗
小众软件
小众软件
V
Visual Studio Blog
月光博客
月光博客
Stack Overflow Blog
Stack Overflow Blog
The GitHub Blog
The GitHub Blog
Recorded Future
Recorded Future
J
Java Code Geeks
雷峰网
雷峰网
P
Privacy & Cybersecurity Law Blog
C
Cisco Blogs
C
Cyber Attacks, Cyber Crime and Cyber Security
AWS News Blog
AWS News Blog
Webroot Blog
Webroot Blog
美团技术团队
N
News | PayPal Newsroom
G
Google Developers Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
博客园_首页
V
Vulnerabilities – Threatpost

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Sending SMS from AWS Lambda
Gunnar Grosch · 2026-05-29 · via DEV Community

A user places an order. Your backend processes it, updates the database, and fires an event. Somewhere in that chain, you want to send them a text message: "Your order is confirmed. It ships tomorrow."

Or maybe it's 2 AM and a CloudWatch alarm just fired. You need an on-call engineer to know about it right now, not when they next check their email.

Or a long-running job just finished processing a large file. The user who submitted it hours ago should know it's ready.

In all of these cases, the pattern is the same: something happens, and you need to send an SMS as part of the response. Lambda is the natural fit for event-driven logic, whether the trigger comes from within AWS or from an external system. You just need a way to get a text message out.

Sinch's Conversation API handles SMS, WhatsApp, RCS, and more through a single endpoint. Your Lambda function won't change if you add channels later.

The post walks through building a Lambda function in TypeScript and Python that sends an SMS using the Sinch Conversation API. Credentials are stored in SSM Parameter Store. The handler is structured so it can be wired to whatever triggers you need: direct invocation, SQS, EventBridge, SNS, or API Gateway.

Prerequisites

The Sinch dashboard setup takes about 10 minutes. After that, sending is a single API call. You'll need a Sinch account (sign up here, a trial account is enough to test, see pricing for details), the AWS SAM CLI, and Node.js 22+ or Python 3.13+.

When you first sign up, Sinch shows an onboarding wizard. If you completed it and selected SMS, you likely already have an app configured with a sender number. In that case, skip to step 4 below. If you dismissed the wizard or are not sure, follow all steps.

Before writing any code, configure the following in the Sinch Build Dashboard:

  1. Get access to Conversation API. Click Conversation API in the left menu, accept the terms, and click GET ACCESS.
  2. Create a Conversation API app. Go to Conversation API > Apps and click Create app. Record the app ID.
  3. Enable the SMS channel on your app. Open the app, find SMS in the channel list, click Set up channel, and connect your service plan.
  4. Find your sender number. Go to SMS > SMS Channel > Numbers. The assigned number is your SMS_SENDER value.
  5. Note your project ID. Click the project name in the top bar and go to Project Settings.
  6. Create an access key. Go to Settings > Access Keys. Record the access key ID and secret. The secret is only shown once.

Note: on a trial account, you can only send to verified numbers and the message content is fixed. To send to any number with custom content, upgrade your account.

One thing that trips people up: the Conversation API is regional. Your app must be created in the same region as your SMS service plan. If they're in different regions, messages will fail with no obvious error. The most common regions are us and eu. A Brazil region (br) also exists.

Storing credentials in SSM Parameter Store

The Lambda function reads your Sinch access key and secret from SSM Parameter Store at cold start. Storing them there as SecureString keeps them out of CloudFormation state and encrypted at rest using KMS.

Create the two parameters before deploying. Run these in the same AWS region where you'll deploy the Lambda:

aws ssm put-parameter \
  --name /sinch/access-key \
  --value "YOUR_ACCESS_KEY" \
  --type SecureString

aws ssm put-parameter \
  --name /sinch/access-key-secret \
  --value "YOUR_ACCESS_KEY_SECRET" \
  --type SecureString

The Lambda function

The structure is the same in both languages: module-level caches for credentials and the OAuth token, a send_sms / sendSms function that owns the validation and API call, and a thin handler that adapts the event.

TypeScript

import { SSMClient, GetParameterCommand } from "@aws-sdk/client-ssm";
import { SQSEvent, SQSBatchResponse, EventBridgeEvent, SNSEvent } from "aws-lambda";

const ssm = new SSMClient({});
const SINCH_REGION = process.env.SINCH_REGION || "us";
const SINCH_PROJECT_ID = process.env.SINCH_PROJECT_ID!;
const SINCH_APP_ID = process.env.SINCH_APP_ID!;
const SINCH_SMS_SENDER = process.env.SINCH_SMS_SENDER!;
const SINCH_ACCESS_KEY_PARAM = process.env.SINCH_ACCESS_KEY_PARAM!;
const SINCH_ACCESS_KEY_SECRET_PARAM = process.env.SINCH_ACCESS_KEY_SECRET_PARAM!;

// Cached at module level. Reused across warm invocations regardless of trigger type
let credentials: { accessKey: string; accessKeySecret: string } | null = null;
let cachedToken: { value: string; expiresAt: number } | null = null;

async function getCredentials() {
  if (credentials) return credentials;
  const [keyRes, secretRes] = await Promise.all([
    ssm.send(new GetParameterCommand({ Name: SINCH_ACCESS_KEY_PARAM, WithDecryption: true })),
    ssm.send(new GetParameterCommand({ Name: SINCH_ACCESS_KEY_SECRET_PARAM, WithDecryption: true })),
  ]);
  credentials = {
    accessKey: keyRes.Parameter!.Value!,
    accessKeySecret: secretRes.Parameter!.Value!,
  };
  return credentials;
}

async function getAccessToken(): Promise<string> {
  const now = Date.now();
  if (cachedToken && now < cachedToken.expiresAt) return cachedToken.value; // Refreshes automatically when expired

  const { accessKey, accessKeySecret } = await getCredentials();
  const encoded = Buffer.from(`${accessKey}:${accessKeySecret}`).toString("base64");

  // Exchange credentials for a short-lived OAuth 2.0 Bearer token (valid ~1 hour).
  // Basic auth is rate-limited and for testing only. Don't use it directly on the Sinch API.
  const response = await fetch("https://auth.sinch.com/oauth2/token", {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      Authorization: `Basic ${encoded}`,
    },
    body: "grant_type=client_credentials",
  });

  if (!response.ok) throw new Error(`Token request failed: ${await response.text()}`);

  const data = await response.json() as { access_token: string; expires_in: number };
  cachedToken = { value: data.access_token, expiresAt: now + (data.expires_in - 60) * 1000 };
  return cachedToken.value;
}

const E164_REGEX = /^\+[1-9]\d{1,14}$/;

async function sendSms(to: string, message: string) {
  if (!E164_REGEX.test(to)) {
    throw new Error(`Invalid phone number format. Use E.164 (e.g. +15551234567), got: ${to}`);
  }

  const token = await getAccessToken();

  const response = await fetch(
    `https://${SINCH_REGION}.conversation.api.sinch.com/v1/projects/${SINCH_PROJECT_ID}/messages:send`,
    {
      method: "POST",
      headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
      body: JSON.stringify({
        app_id: SINCH_APP_ID,
        recipient: { identified_by: { channel_identities: [{ channel: "SMS", identity: to }] } },
        message: { text_message: { text: message } },
        channel_properties: { SMS_SENDER: SINCH_SMS_SENDER },
      }),
    }
  );

  if (!response.ok) {
    const error = await response.text();
    throw new Error(`Sinch API error ${response.status}: ${error}`);
  }

  return response.json();
}

// --- Direct invocation (default) ---
export const handler = async (event: { to: string; message: string }) => {
  if (!event.to || !event.message) {
    return { statusCode: 400, body: "Missing to or message" };
  }
  try {
    return { statusCode: 200, body: await sendSms(event.to, event.message) };
  } catch (err) {
    console.error(err);
    return { statusCode: 500, body: String(err) };
  }
};

// --- SQS (uncomment to use) ---
// Message body format: { "to": "+15551234567", "message": "Hello!" }
// Returns batchItemFailures so only failed records are retried, preventing duplicate sends.
//
// export const handler = async (event: SQSEvent): Promise<SQSBatchResponse> => {
//   const failures: { itemIdentifier: string }[] = [];
//   for (const record of event.Records) {
//     try {
//       const payload = JSON.parse(record.body);
//       await sendSms(payload.to, payload.message);
//     } catch (err) {
//       console.error(`Failed record ${record.messageId}:`, err);
//       failures.push({ itemIdentifier: record.messageId });
//     }
//   }
//   return { batchItemFailures: failures };
// };

// --- EventBridge (uncomment to use) ---
// Event detail format: { "to": "+15551234567", "message": "Hello!" }
//
// export const handler = async (
//   event: EventBridgeEvent<"SendSms", { to: string; message: string }>
// ) => {
//   await sendSms(event.detail.to, event.detail.message);
// };

// --- SNS (uncomment to use) ---
// SNS message body format: { "to": "+15551234567", "message": "Hello!" }
//
// export const handler = async (event: SNSEvent) => {
//   for (const record of event.Records) {
//     const payload = JSON.parse(record.Sns.Message);
//     await sendSms(payload.to, payload.message);
//   }
// };

Python

import json
import os
import re
import time
import urllib.request
import urllib.error
from base64 import b64encode
import boto3

ssm = boto3.client("ssm")

SINCH_REGION = os.environ.get("SINCH_REGION", "us")
SINCH_PROJECT_ID = os.environ["SINCH_PROJECT_ID"]
SINCH_APP_ID = os.environ["SINCH_APP_ID"]
SINCH_SMS_SENDER = os.environ["SINCH_SMS_SENDER"]
SINCH_ACCESS_KEY_PARAM = os.environ["SINCH_ACCESS_KEY_PARAM"]
SINCH_ACCESS_KEY_SECRET_PARAM = os.environ["SINCH_ACCESS_KEY_SECRET_PARAM"]

E164_REGEX = re.compile(r"^\+[1-9]\d{1,14}$")

# Module-level cache. Shared across warm invocations regardless of trigger type
_credentials = None
_token_cache = {"value": None, "expires_at": 0}


def get_credentials():
    global _credentials
    if _credentials:
        return _credentials
    key = ssm.get_parameter(Name=SINCH_ACCESS_KEY_PARAM, WithDecryption=True)["Parameter"]["Value"]
    secret = ssm.get_parameter(Name=SINCH_ACCESS_KEY_SECRET_PARAM, WithDecryption=True)["Parameter"]["Value"]
    _credentials = (key, secret)
    return _credentials


def get_access_token():
    now = time.time()
    if _token_cache["value"] and now < _token_cache["expires_at"]:
        return _token_cache["value"]

    access_key, access_key_secret = get_credentials()
    encoded = b64encode(f"{access_key}:{access_key_secret}".encode()).decode()

    req = urllib.request.Request(
        "https://auth.sinch.com/oauth2/token",
        data=b"grant_type=client_credentials",
        headers={
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization": f"Basic {encoded}",
        },
        method="POST",
    )
    try:
        with urllib.request.urlopen(req) as resp:
            data = json.loads(resp.read())
    except urllib.error.HTTPError as e:
        raise RuntimeError(f"Token request failed {e.code}: {e.read().decode()}")

    _token_cache["value"] = data["access_token"]
    _token_cache["expires_at"] = now + data["expires_in"] - 60
    return _token_cache["value"]


def send_sms(to, message):
    if not E164_REGEX.match(to):
        raise ValueError(f"Invalid phone number format. Use E.164 (e.g. +15551234567), got: {to}")

    token = get_access_token()
    payload = json.dumps({
        "app_id": SINCH_APP_ID,
        "recipient": {"identified_by": {"channel_identities": [{"channel": "SMS", "identity": to}]}},
        "message": {"text_message": {"text": message}},
        "channel_properties": {"SMS_SENDER": SINCH_SMS_SENDER},
    }).encode()

    url = f"https://{SINCH_REGION}.conversation.api.sinch.com/v1/projects/{SINCH_PROJECT_ID}/messages:send"
    req = urllib.request.Request(
        url, data=payload,
        headers={"Content-Type": "application/json", "Authorization": f"Bearer {token}"},
        method="POST",
    )
    try:
        with urllib.request.urlopen(req) as response:
            return json.loads(response.read())
    except urllib.error.HTTPError as e:
        error = e.read().decode()
        print(f"Sinch API error: {error}")
        raise RuntimeError(f"Sinch API error {e.code}: {error}")


# --- Direct invocation (default) ---
def handler(event, context):
    to = event.get("to")
    message = event.get("message")
    if not to or not message:
        return {"statusCode": 400, "body": "Missing to or message"}
    try:
        return {"statusCode": 200, "body": send_sms(to, message)}
    except Exception as e:
        print(f"Error: {e}")
        return {"statusCode": 500, "body": str(e)}


# --- SQS (uncomment to use) ---
# Message body format: {"to": "+15551234567", "message": "Hello!"}
# Returns batchItemFailures so only failed records are retried, preventing duplicate sends.
#
# def handler(event, context):
#     failures = []
#     for record in event["Records"]:
#         try:
#             payload = json.loads(record["body"])
#             send_sms(payload["to"], payload["message"])
#         except Exception as e:
#             print(f"Failed record {record['messageId']}: {e}")
#             failures.append({"itemIdentifier": record["messageId"]})
#     return {"batchItemFailures": failures}


# --- EventBridge (uncomment to use) ---
# Event detail format: {"to": "+15551234567", "message": "Hello!"}
#
# def handler(event, context):
#     detail = event["detail"]
#     send_sms(detail["to"], detail["message"])


# --- SNS (uncomment to use) ---
# SNS message body format: {"to": "+15551234567", "message": "Hello!"}
#
# def handler(event, context):
#     for record in event["Records"]:
#         payload = json.loads(record["Sns"]["Message"])
#         send_sms(payload["to"], payload["message"])

The SAM template

The repo uses a single template.yaml at the root that deploys all four functions together (Node.js and Python, raw HTTP and SDK). Here's the relevant section for the Node.js raw HTTP function:

AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31

Globals:
  Function:
    Timeout: 10
    MemorySize: 256
    Environment:
      Variables:
        SINCH_REGION: !Ref SinchRegion
        SINCH_PROJECT_ID: !Ref SinchProjectId
        SINCH_APP_ID: !Ref SinchAppId
        SINCH_SMS_SENDER: !Ref SinchSmsSender
        SINCH_ACCESS_KEY_PARAM: !Ref SinchAccessKeyParam
        SINCH_ACCESS_KEY_SECRET_PARAM: !Ref SinchAccessKeySecretParam

Parameters:
  SinchRegion:
    Type: String
    Default: us
    AllowedValues: [us, eu]
  # ... SinchProjectId, SinchAppId, SinchSmsSender,
  #     SinchAccessKeyParam, SinchAccessKeySecretParam

Resources:
  NodeHttpFunction:
    Type: AWS::Serverless::Function
    Properties:
      Runtime: nodejs22.x
      Handler: src/handler.handler
      CodeUri: node-http/
      Policies:
        - Statement:
            - Effect: Allow
              Action: ssm:GetParameter
              Resource:
                - !Sub "arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter${SinchAccessKeyParam}"
                - !Sub "arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter${SinchAccessKeySecretParam}"
    Metadata:
      BuildMethod: esbuild
      BuildProperties:
        Minify: false
        Target: es2022
        EntryPoints:
          - node-http/src/handler.ts

Deploy from the repo root:

sam build
sam deploy --guided

SAM handles all dependencies automatically during sam build: Node.js packages via npm install, Python packages via requirements.txt.

Invoking the function

With no event source attached, you invoke the function directly with a JSON payload. The simplest way is the AWS CLI:

# Get the function name from the stack outputs after sam deploy --guided,
# then invoke it:
aws lambda invoke \
  --function-name <NodeHttpFunctionName from outputs> \
  --payload '{"to": "+15559876543", "message": "Hello from Lambda!"}' \
  --cli-binary-format raw-in-base64-out \
  response.json

cat response.json

A successful response looks like:

{
  "statusCode": 200,
  "body": {
    "accepted_time": "2026-05-27T18:00:00.000Z",
    "message_id": "01ABC123DEF456GHI789JKL012"
  }
}

message_id is what you'd use to correlate delivery receipts if you set up a webhook.

If something goes wrong, the Sinch API returns a structured error:

{
  "statusCode": 400,
  "body": "{\"error\":{\"code\":400,\"message\":\"recipient identity is not a valid MSISDN\",\"status\":\"INVALID_ARGUMENT\"}}"
}

Common causes: malformed phone number, wrong app_id, region mismatch between your app and service plan, or missing SMS_SENDER without a default originator configured.

When you're ready to wire it up to something, change only the handler signature. sendSms() doesn't change. The SAM template has commented event source blocks for SQS, EventBridge, SNS, and API Gateway ready to uncomment:

  • SQS for queued, rate-controlled sending
  • EventBridge for event-driven notifications from other AWS services (order placed, alarm fired, job completed)
  • SNS for fan-out scenarios where multiple subscribers need to react
  • API Gateway if you need an HTTP endpoint for third-party webhooks or client-side triggers

Testing locally

Create an event file:

{
  "to": "+15559876543",
  "message": "Test from local"
}

Then invoke locally with SAM:

sam local invoke NodeHttpFunction --event event.json
# or
sam local invoke PythonHttpFunction --event event.json

Note: sam local invoke won't be able to reach SSM or the Sinch API unless your local environment has AWS credentials with the right permissions. For local testing without live credentials, stub the SSM calls or use environment variables directly.

Things worth knowing

Phone numbers must be E.164

The to value must be in E.164 format: +15551234567, not 5551234567 or (555) 123-4567. The handler validates this before calling the API. The Sinch API won't normalize it for you.

Long messages get split

SMS has a 160-character limit for standard GSM encoding. Longer messages get split into multiple parts. You can cap this with SMS_MAX_NUMBER_OF_MESSAGE_PARTS in channel_properties:

"channel_properties": {
  "SMS_SENDER": "+15551231234",
  "SMS_MAX_NUMBER_OF_MESSAGE_PARTS": "2"
}

If the message would require more parts than the cap, the API rejects it. It won't truncate or silently drop it. You'll get an error back, so you can handle it in your application.

Error handling and delivery status

When sendSms() throws, the handler logs the error and returns a 500. If the Lambda is invoked asynchronously (EventBridge, SNS), Lambda will retry up to two more times by default before sending the event to a dead-letter queue if one is configured. If you're sending high volumes, set up a DLQ on the function so failed sends don't disappear silently.

For SQS triggers, be aware of partial batch failures. If one message in a batch fails, the entire batch is retried by default, which means already-sent messages get sent again. To avoid duplicate SMS, implement partial batch failure reporting: catch errors per record and return { batchItemFailures: [{ itemIdentifier: record.messageId }] } so only the failed records are retried. The SQS handler variant in the code has a comment pointing to this.

For true end-to-end idempotency, you need deduplication before the Sinch call since the Conversation API doesn't support idempotency keys. Use an SQS FIFO queue with a MessageDeduplicationId derived from your business event, or the Powertools for AWS Lambda idempotency utility which handles a DynamoDB check-before-send with a decorator.

For delivery status on the recipient's device, the Conversation API sends a callback to a webhook URL you configure on your app. The status will be either DELIVERED or FAILED. To receive these, register a webhook in the Sinch Build Dashboard under your app's webhook settings, or via the Webhooks API. That's a natural next step once this is working.

The SDK and other languages

This post uses raw HTTP. The tradeoff compared to the official Sinch SDKs (Node.js, Python, Java, .NET): raw HTTP has zero runtime dependencies and the auth flow is visible in the code. The SDKs remove the token caching code entirely (they handle OAuth 2.0 internally) but add a dependency. Both are valid. The repo includes node-sdk and python-sdk examples alongside the raw HTTP ones.

Wrapping up

The function is deployed, the credentials are in SSM, and you have a handler that works with whatever trigger makes sense for your use case.

The natural next step is delivery receipts: configuring a webhook so your app knows whether each message actually reached the recipient's device. After that, if you need to send to many recipients, wiring an SQS queue in front of the function gives you rate control and automatic retries without changing the handler.

The source code for this post is available on GitHub: gunnargrosch/sinch-sms-lambda

What are you building that needs SMS notifications? Let me know in the comments.

Additional Resources