SNS SMS management provides comprehensive functionality for sending SMS messages, managing SMS attributes, handling phone number opt-outs, and working with SMS sandbox environments for testing.
Configure global SMS settings including default SMS type, delivery status logging, and spending limits.
/**
* Retrieves SMS attributes for the AWS account
* Returns configuration for SMS delivery and billing
*/
class GetSMSAttributesCommand {
constructor(input?: GetSMSAttributesInput);
}
interface GetSMSAttributesInput {
/** List of attribute names to retrieve (optional - returns all if not specified) */
attributes?: string[];
}
interface GetSMSAttributesResponse {
/** Map of SMS attribute names to values */
attributes?: SMSAttributesMap;
}
interface SMSAttributesMap {
[key: string]: string;
}Common SMS Attributes:
MonthlySpendLimit: Maximum USD amount to spend on SMS per monthDeliveryStatusIAMRole: IAM role ARN for delivery status loggingDeliveryStatusSuccessSamplingRate: Success delivery status sampling rate (0-100)DefaultSMSType: Default SMS type ("Promotional" or "Transactional")DefaultSenderID: Default sender ID for SMS messagesUsageReportS3Bucket: S3 bucket for SMS usage reportsUsage Example:
import { SNSClient, GetSMSAttributesCommand } from "@aws-sdk/client-sns";
const client = new SNSClient({ region: "us-east-1" });
// Get all SMS attributes
const allAttributes = await client.send(new GetSMSAttributesCommand());
console.log("Monthly Spend Limit:", allAttributes.attributes?.MonthlySpendLimit);
console.log("Default SMS Type:", allAttributes.attributes?.DefaultSMSType);
// Get specific attributes
const specificAttributes = await client.send(new GetSMSAttributesCommand({
attributes: ["MonthlySpendLimit", "DefaultSMSType", "DeliveryStatusIAMRole"]
}));Configure SMS settings for the AWS account.
/**
* Sets SMS attributes for the AWS account
* Configures global SMS delivery and billing settings
*/
class SetSMSAttributesCommand {
constructor(input: SetSMSAttributesInput);
}
interface SetSMSAttributesInput {
/** Map of SMS attributes to set */
attributes: SMSAttributesMap;
}
interface SetSMSAttributesResponse {
/** Status message */
ResponseMetadata?: any;
}Usage Examples:
// Set monthly spending limit
await client.send(new SetSMSAttributesCommand({
attributes: {
MonthlySpendLimit: "100.00" // $100 USD per month
}
}));
// Configure delivery status logging
await client.send(new SetSMSAttributesCommand({
attributes: {
DeliveryStatusIAMRole: "arn:aws:iam::123456789012:role/SNSDeliveryStatusRole",
DeliveryStatusSuccessSamplingRate: "10" // 10% sampling
}
}));
// Set default SMS type and sender ID
await client.send(new SetSMSAttributesCommand({
attributes: {
DefaultSMSType: "Transactional",
DefaultSenderID: "MyCompany"
}
}));
// Configure usage reporting
await client.send(new SetSMSAttributesCommand({
attributes: {
UsageReportS3Bucket: "my-sms-usage-reports"
}
}));Manage phone numbers that have opted out of receiving SMS messages.
/**
* Checks if a phone number is currently opted out of receiving SMS messages
*/
class CheckIfPhoneNumberIsOptedOutCommand {
constructor(input: CheckIfPhoneNumberIsOptedOutInput);
}
interface CheckIfPhoneNumberIsOptedOutInput {
/** Phone number to check (E.164 format) */
phoneNumber: string;
}
interface CheckIfPhoneNumberIsOptedOutResponse {
/** Whether the phone number is opted out */
isOptedOut?: boolean;
}Usage Example:
const optOutStatus = await client.send(new CheckIfPhoneNumberIsOptedOutCommand({
phoneNumber: "+1234567890"
}));
if (optOutStatus.isOptedOut) {
console.log("Phone number is opted out - cannot send SMS");
} else {
console.log("Phone number can receive SMS messages");
}Removes a phone number from the opt-out list, allowing it to receive SMS messages again.
/**
* Opts in a phone number to receive SMS messages
* Removes the number from the opt-out list
*/
class OptInPhoneNumberCommand {
constructor(input: OptInPhoneNumberInput);
}
interface OptInPhoneNumberInput {
/** Phone number to opt in (E.164 format) */
phoneNumber: string;
}
interface OptInPhoneNumberResponse {
/** Confirmation message */
ResponseMetadata?: any;
}Usage Example:
await client.send(new OptInPhoneNumberCommand({
phoneNumber: "+1234567890"
}));
console.log("Phone number has been opted back in");Retrieves a list of phone numbers that are currently opted out of receiving SMS messages.
/**
* Returns a list of phone numbers that are opted out of receiving SMS messages
* Supports pagination for large opt-out lists
*/
class ListPhoneNumbersOptedOutCommand {
constructor(input?: ListPhoneNumbersOptedOutInput);
}
interface ListPhoneNumbersOptedOutInput {
/** Pagination token from previous request */
nextToken?: string;
}
interface ListPhoneNumbersOptedOutResponse {
/** List of opted-out phone numbers */
phoneNumbers?: string[];
/** Token for next page of results */
nextToken?: string;
}Usage Example:
// Get all opted-out numbers
let nextToken: string | undefined;
const allOptedOutNumbers: string[] = [];
do {
const result = await client.send(new ListPhoneNumbersOptedOutCommand({
nextToken: nextToken
}));
if (result.phoneNumbers) {
allOptedOutNumbers.push(...result.phoneNumbers);
}
nextToken = result.nextToken;
} while (nextToken);
console.log("Total opted-out numbers:", allOptedOutNumbers.length);
allOptedOutNumbers.forEach(number => {
console.log("Opted out:", number);
});The SMS Sandbox is a testing environment that allows you to send SMS messages to verified phone numbers without incurring charges or affecting your reputation.
Check whether your account is in the SMS sandbox.
/**
* Retrieves the SMS sandbox account status
* Indicates whether the account is in sandbox mode
*/
class GetSMSSandboxAccountStatusCommand {
constructor(input?: GetSMSSandboxAccountStatusInput);
}
interface GetSMSSandboxAccountStatusInput {}
interface GetSMSSandboxAccountStatusResult {
/** Whether the account is in SMS sandbox mode */
IsInSandbox?: boolean;
}Usage Example:
const sandboxStatus = await client.send(new GetSMSSandboxAccountStatusCommand());
if (sandboxStatus.IsInSandbox) {
console.log("Account is in SMS sandbox mode - can only send to verified numbers");
} else {
console.log("Account has production SMS access");
}Add a phone number to the SMS sandbox for testing purposes.
/**
* Creates an SMS sandbox phone number for testing
* Initiates verification process for the phone number
*/
class CreateSMSSandboxPhoneNumberCommand {
constructor(input: CreateSMSSandboxPhoneNumberInput);
}
interface CreateSMSSandboxPhoneNumberInput {
/** Phone number to add to sandbox (E.164 format) */
PhoneNumber: string;
/** Language code for verification message */
LanguageCode?: LanguageCodeString;
}
interface CreateSMSSandboxPhoneNumberResult {
/** Status message */
ResponseMetadata?: any;
}Usage Example:
await client.send(new CreateSMSSandboxPhoneNumberCommand({
PhoneNumber: "+1234567890",
LanguageCode: "en-US"
}));
console.log("Verification SMS sent to phone number");Complete the verification process for a sandbox phone number using the verification code.
/**
* Verifies an SMS sandbox phone number using the verification code
* Completes the sandbox phone number registration
*/
class VerifySMSSandboxPhoneNumberCommand {
constructor(input: VerifySMSSandboxPhoneNumberInput);
}
interface VerifySMSSandboxPhoneNumberInput {
/** Phone number to verify */
PhoneNumber: string;
/** Verification code received via SMS */
OneTimePassword: string;
}
interface VerifySMSSandboxPhoneNumberResult {
/** Status message */
ResponseMetadata?: any;
}Usage Example:
await client.send(new VerifySMSSandboxPhoneNumberCommand({
PhoneNumber: "+1234567890",
OneTimePassword: "123456" // Code received via SMS
}));
console.log("Phone number verified for SMS sandbox");Retrieve all verified phone numbers in the SMS sandbox.
/**
* Returns a list of verified SMS sandbox phone numbers
* Shows verification status for each number
*/
class ListSMSSandboxPhoneNumbersCommand {
constructor(input?: ListSMSSandboxPhoneNumbersInput);
}
interface ListSMSSandboxPhoneNumbersInput {
/** Pagination token from previous request */
NextToken?: string;
/** Maximum number of results to return */
MaxItems?: number;
}
interface ListSMSSandboxPhoneNumbersResult {
/** List of sandbox phone numbers */
PhoneNumbers?: SMSSandboxPhoneNumber[];
/** Token for next page of results */
NextToken?: string;
}
interface SMSSandboxPhoneNumber {
/** Phone number */
PhoneNumber?: string;
/** Verification status */
Status?: SMSSandboxPhoneNumberVerificationStatus;
}
enum SMSSandboxPhoneNumberVerificationStatus {
Pending = "Pending",
Verified = "Verified"
}Usage Example:
const sandboxNumbers = await client.send(new ListSMSSandboxPhoneNumbersCommand());
sandboxNumbers.PhoneNumbers?.forEach(phoneNumber => {
console.log(`${phoneNumber.PhoneNumber}: ${phoneNumber.Status}`);
});Remove a phone number from the SMS sandbox.
/**
* Deletes an SMS sandbox phone number
* Removes the number from the verified sandbox list
*/
class DeleteSMSSandboxPhoneNumberCommand {
constructor(input: DeleteSMSSandboxPhoneNumberInput);
}
interface DeleteSMSSandboxPhoneNumberInput {
/** Phone number to remove from sandbox */
PhoneNumber: string;
}
interface DeleteSMSSandboxPhoneNumberResult {
/** Status message */
ResponseMetadata?: any;
}Usage Example:
await client.send(new DeleteSMSSandboxPhoneNumberCommand({
PhoneNumber: "+1234567890"
}));
console.log("Phone number removed from SMS sandbox");Manage dedicated origination numbers for SMS sending.
Retrieve origination numbers available for SMS sending with detailed information about each number.
/**
* Returns a list of origination numbers and their properties
* Shows dedicated phone numbers available for SMS sending
*/
class ListOriginationNumbersCommand {
constructor(input?: ListOriginationNumbersRequest);
}
interface ListOriginationNumbersRequest {
/** Pagination token from previous request */
NextToken?: string;
/** Maximum number of results to return */
MaxResults?: number;
}
interface ListOriginationNumbersResult {
/** List of origination numbers */
PhoneNumbers?: PhoneNumberInformation[];
/** Token for next page of results */
NextToken?: string;
}
interface PhoneNumberInformation {
/** Phone number in E.164 format */
PhoneNumber?: string;
/** Status of the phone number */
Status?: string;
/** ISO country code */
Iso2CountryCode?: string;
/** Capabilities of the phone number */
NumberCapabilities?: NumberCapability[];
/** Route type for SMS delivery */
RouteType?: RouteType;
/** Monthly leasing price in USD */
MonthlyLeasingPrice?: string;
}
enum NumberCapability {
MMS = "MMS",
SMS = "SMS",
VOICE = "VOICE"
}
enum RouteType {
Premium = "Premium",
Promotional = "Promotional",
Transactional = "Transactional"
}Usage Example:
const originationNumbers = await client.send(new ListOriginationNumbersCommand());
originationNumbers.PhoneNumbers?.forEach(phoneInfo => {
console.log(`Number: ${phoneInfo.PhoneNumber}`);
console.log(`Country: ${phoneInfo.Iso2CountryCode}`);
console.log(`Capabilities: ${phoneInfo.NumberCapabilities?.join(', ')}`);
console.log(`Route Type: ${phoneInfo.RouteType}`);
console.log(`Monthly Price: $${phoneInfo.MonthlyLeasingPrice}`);
console.log('---');
});Configure the type of SMS messages for optimal delivery and compliance.
Promotional SMS:
Transactional SMS:
Different routing options for SMS delivery:
Transactional Route:
Promotional Route:
Premium Route:
SMS with Opt-Out Handling:
import { PublishCommand } from "@aws-sdk/client-sns";
const sendSMSWithOptOutCheck = async (phoneNumber: string, message: string) => {
// Check if number is opted out
const optOutStatus = await client.send(new CheckIfPhoneNumberIsOptedOutCommand({
phoneNumber: phoneNumber
}));
if (optOutStatus.isOptedOut) {
console.log(`Cannot send SMS to ${phoneNumber} - number is opted out`);
return null;
}
// Send SMS message
const result = await client.send(new PublishCommand({
PhoneNumber: phoneNumber,
Message: message,
MessageAttributes: {
'AWS.SNS.SMS.SMSType': {
DataType: 'String',
StringValue: 'Transactional'
},
'AWS.SNS.SMS.SenderID': {
DataType: 'String',
StringValue: 'MyCompany'
}
}
}));
return result.MessageId;
};Bulk SMS with Error Handling:
const sendBulkSMS = async (phoneNumbers: string[], message: string) => {
const results = await Promise.allSettled(
phoneNumbers.map(async (phoneNumber) => {
try {
const messageId = await sendSMSWithOptOutCheck(phoneNumber, message);
return { phoneNumber, messageId, status: 'sent' };
} catch (error) {
return { phoneNumber, error: error.message, status: 'failed' };
}
})
);
const successful = results.filter(r => r.status === 'fulfilled' && r.value.status === 'sent');
const failed = results.filter(r => r.status === 'rejected' || r.value.status === 'failed');
console.log(`SMS Results: ${successful.length} sent, ${failed.length} failed`);
return { successful, failed };
};SMS Sandbox Testing Flow:
const setupSMSSandboxTesting = async (testPhoneNumber: string) => {
// Check if account is in sandbox
const sandboxStatus = await client.send(new GetSMSSandboxAccountStatusCommand());
if (!sandboxStatus.IsInSandbox) {
console.log("Account has production SMS access");
return;
}
// Add phone number to sandbox
await client.send(new CreateSMSSandboxPhoneNumberCommand({
PhoneNumber: testPhoneNumber,
LanguageCode: "en-US"
}));
console.log(`Verification SMS sent to ${testPhoneNumber}`);
console.log("Enter verification code when received:");
// In a real application, you would get this from user input
const verificationCode = "123456"; // Replace with actual code
await client.send(new VerifySMSSandboxPhoneNumberCommand({
PhoneNumber: testPhoneNumber,
OneTimePassword: verificationCode
}));
console.log("Phone number verified for sandbox testing");
};