вариант
ДомДом Skill Разработка API azure-communication-sms-java

azure-communication-sms-java

microsoft/skills microsoft/skills

Отправляйте SMS-сообщения одному или нескольким получателям с отчетом о доставке с помощью Java SDK для SMS-сервисов Azure Communication Services.

...Расширить все
1
Обновлено время 14 сентября 2026 г.

Azure Communication SMS (Java)

Отправка SMS-сообщений одному или нескольким получателям с отчетом о доставке.

Установка


    com.azure
    azure-communication-sms
    1.2.0

Создание клиента

import com.azure.communication.sms.SmsClient;
import com.azure.communication.sms.SmsClientBuilder;
import com.azure.core.credential.TokenCredential;
import com.azure.identity.AzureIdentityEnvVars;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;

// Локальная среда разработки: DefaultAzureCredential. Производственная среда: установите AZURE_TOKEN_CREDENTIALS=prod или AZURE_TOKEN_CREDENTIALS=
TokenCredential credential = new DefaultAzureCredentialBuilder()
    .requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
    .build();
// Или используйте конкретные учетные данные напрямую в производственной среде:
// См. https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();

// С использованием DefaultAzureCredential (рекомендуется)
SmsClient smsClient = new SmsClientBuilder()
    .endpoint("https://.communication.azure.com")
    .credential(credential)
    .buildClient();

// С использованием строки подключения
SmsClient smsClient = new SmsClientBuilder()
    .connectionString("")
    .buildClient();

// С использованием AzureKeyCredential
import com.azure.core.credential.AzureKeyCredential;

SmsClient smsClient = new SmsClientBuilder()
    .endpoint("https://.communication.azure.com")
    .credential(new AzureKeyCredential(""))
    .buildClient();

// Асинхронный клиент
SmsAsyncClient smsAsyncClient = new SmsClientBuilder()
    .connectionString("")
    .buildAsyncClient();

Отправка SMS одному получателю

import com.azure.communication.sms.models.SmsSendResult;

// Простая отправка
SmsSendResult result = smsClient.send(
    "+14255550100",      // От (ваш номер телефона ACS)
    "+14255551234",      // Получатель
    "Ваш проверочный код: 123456");

System.out.println("Идентификатор сообщения: " + result.getMessageId());
System.out.println("Кому: " + result.getTo());
System.out.println("Успешно: " + result.isSuccessful());

if (!result.isSuccessful()) {
    System.out.println("Ошибка: " + result.getErrorMessage());
    System.out.println("Статус: " + result.getHttpStatusCode());
}

Отправка SMS нескольким получателям

import com.azure.communication.sms.models.SmsSendOptions;
import java.util.Arrays;
import java.util.List;

List recipients = Arrays.asList(
    "+14255551111",
    "+14255552222",
    "+14255553333"
);

// С параметрами
SmsSendOptions options = new SmsSendOptions()
    .setDeliveryReportEnabled(true)
    .setTag("marketing-campaign-001");

Iterable results = smsClient.sendWithResponse(
    "+14255550100",      // От
    recipients,          // Список адресатов
    "Флэш-распродажа! Скидка 50% только сегодня.",
    options,
    Context.NONE
).getValue();

for (SmsSendResult result : results) {
    if (result.isSuccessful()) {
        System.out.println("Отправлено " + result.getTo() + ": " + result.getMessageId());
    } else {
        System.out.println("Ошибка при отправке " + result.getTo() + ": " + result.getErrorMessage());
    }
}

Параметры отправки

SmsSendOptions options = new SmsSendOptions();

// Включить отчеты о доставке (отправляются через Event Grid)
options.setDeliveryReportEnabled(true);

// Добавить пользовательский тег для отслеживания
options.setTag("order-confirmation-12345");

Обработка ответа

import com.azure.core.http.rest.Response;

Response<Iterable> response = smsClient.sendWithResponse(
    "+14255550100",
    Arrays.asList("+14255551234"),
    "Hello!",
    new SmsSendOptions().setDeliveryReportEnabled(true),
    Context.NONE
);

// Проверка HTTP-ответа
System.out.println("Код статуса: " + response.getStatusCode());
System.out.println("Заголовки: " + response.getHeaders());

// Обработка результатов
for (SmsSendResult result : response.getValue()) {
    System.out.println("Идентификатор сообщения: " + result.getMessageId());
    System.out.println("Успешно: " + result.isSuccessful());
    
    if (!result.isSuccessful()) {
        System.out.println("Статус HTTP: " + result.getHttpStatusCode());
        System.out.println("Ошибка: " + result.getErrorMessage());
    }
}

Асинхронные операции

import reactor.core.publisher.Mono;

SmsAsyncClient asyncClient = new SmsClientBuilder()
    .connectionString("")
    .buildAsyncClient();

// Отправить одно сообщение
asyncClient.send("+14255550100", "+14255551234", "Асинхронное сообщение!")
    .subscribe(
        result -> System.out.println("Отправлено: " + result.getMessageId()),
        error -> System.out.println("Ошибка: " + error.getMessage())
    );

// Отправка нескольким получателям с параметрами
SmsSendOptions options = new SmsSendOptions()
    .setDeliveryReportEnabled(true);

asyncClient.sendWithResponse(
    "+14255550100",
    Arrays.asList("+14255551111", "+14255552222"),
    "Массовая асинхронная рассылка",
    options)
    .subscribe(response -> {
        for (SmsSendResult result : response.getValue()) {
            System.out.println("Результат: " + result.getTo() + " - " + result.isSuccessful());
        }
    });

Обработка ошибок

import com.azure.core.exception.HttpResponseException;

try {
    SmsSendResult result = smsClient.send(
        "+14255550100",
        "+14255551234",
        "Тестовое сообщение"
    );
    
    // Ошибки отдельных сообщений не вызывают исключений
    if (!result.isSuccessful()) {
        handleMessageError(result);
    }
    
} catch (HttpResponseException e) {
    // Сбои на уровне запроса (аутентификация, сеть и т. д.)
    System.out.println("Запрос завершился сбоем: " + e.getMessage());
    System.out.println("Статус: " + e.getResponse().getStatusCode());
} catch (RuntimeException e) {
    System.out.println("Неожиданная ошибка: " + e.getMessage());
}

private void handleMessageError(SmsSendResult result) {
    int status = result.getHttpStatusCode();
    String error = result.getErrorMessage();
    
    if (status == 400) {
        System.out.println("Неверный номер телефона: " + result.getTo());
    } else if (status == 429) {
        System.out.println("Ограничение частоты запросов — попробуйте позже");
    } else {
        System.out.println("Ошибка " + status + ": " + error);
    }
}

Отчёты о доставке

Отчеты о доставке отправляются через Azure Event Grid. Настройте подписку Event Grid для вашего ресурса ACS.

// Обработчик веб-хука Event Grid (в вашем конечной точке)
public void handleDeliveryReport(String eventJson) {
    // Анализ события Event Grid
    // Тип события: Microsoft.Communication.SMSDeliveryReportReceived
    
    // Данные события содержат:
    // - messageId: соответствует SmsSendResult.getMessageId()
    // - from: номер отправителя
    // - to: номер получателя
    // - deliveryStatus: «Delivered», «Failed» и т. д.
    // - deliveryStatusDetails: подробный статус
    // - receivedTimestamp: время получения статуса
    // - tag: ваш пользовательский тег из SmsSendOptions
}

Свойства SmsSendResult

Свойство Тип Описание
getMessageId() Строка Уникальный идентификатор сообщения
getTo() String Номер телефона получателя
isSuccessful() логическое значение Успешна ли отправка
getHttpStatusCode() int Статус HTTP для данного получателя
getErrorMessage() String Подробности ошибки в случае сбоя
getRepeatabilityResult() RepeatabilityResult Результат проверки идемпотентности

Переменные среды

AZURE_COMMUNICATION_ENDPOINT=https://.communication.azure.com  # Требуется для всех методов аутентификации
AZURE_COMMUNICATION_CONNECTION_STRING=endpoint=https://...;accesskey=...  # Альтернатива аутентификации с помощью Entra ID
SMS_FROM_NUMBER=+14255550100  # Требуется для указания номера телефона отправителя
AZURE_TOKEN_CREDENTIALS=prod  # Требуется только в том случае, если в производственной среде используется DefaultAzureCredential

Рекомендации

  1. Формат номера телефона — используйте формат E.164: +[код страны][номер]
  2. Отчеты о доставке — включите для критически важных сообщений (OTP, оповещения)
  3. Теги — используйте теги для сопоставления сообщений с бизнес-контекстом
  4. Обработка ошибок — проверяйте isSuccessful() для каждого получателя отдельно
  5. Ограничение частоты отправки — реализуйте повторные попытки с интервалом отсрочки при получении ответов 429
  6. Массовая рассылка — используйте пакетную отправку для нескольких получателей (это более эффективно)

Фразы-триггеры

  • «отправить SMS на Java», «текстовое сообщение на Java»
  • «SMS-уведомление», «SMS с одноразовым паролем», «массовая рассылка SMS»
  • «отчет о доставке SMS», «SMS в Azure Communication Services»
Посмотреть на GitHub
---
name: azure-communication-sms-java
description: Send SMS messages to single or multiple recipients with delivery reporting using the Azure Communication Services SMS Java SDK.
license: MIT
---

# Azure Communication SMS (Java)

Send SMS messages to single or multiple recipients with delivery reporting.

## Installation

```xml
<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-communication-sms</artifactId>
    <version>1.2.0</version>
</dependency>
```

## Client Creation

```java
import com.azure.communication.sms.SmsClient;
import com.azure.communication.sms.SmsClientBuilder;
import com.azure.core.credential.TokenCredential;
import com.azure.identity.AzureIdentityEnvVars;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;

// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
TokenCredential credential = new DefaultAzureCredentialBuilder()
    .requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
    .build();
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();

// With DefaultAzureCredential (recommended)
SmsClient smsClient = new SmsClientBuilder()
    .endpoint("https://<resource>.communication.azure.com")
    .credential(credential)
    .buildClient();

// With connection string
SmsClient smsClient = new SmsClientBuilder()
    .connectionString("<connection-string>")
    .buildClient();

// With AzureKeyCredential
import com.azure.core.credential.AzureKeyCredential;

SmsClient smsClient = new SmsClientBuilder()
    .endpoint("https://<resource>.communication.azure.com")
    .credential(new AzureKeyCredential("<access-key>"))
    .buildClient();

// Async client
SmsAsyncClient smsAsyncClient = new SmsClientBuilder()
    .connectionString("<connection-string>")
    .buildAsyncClient();
```

## Send SMS to Single Recipient

```java
import com.azure.communication.sms.models.SmsSendResult;

// Simple send
SmsSendResult result = smsClient.send(
    "+14255550100",      // From (your ACS phone number)
    "+14255551234",      // To
    "Your verification code is 123456");

System.out.println("Message ID: " + result.getMessageId());
System.out.println("To: " + result.getTo());
System.out.println("Success: " + result.isSuccessful());

if (!result.isSuccessful()) {
    System.out.println("Error: " + result.getErrorMessage());
    System.out.println("Status: " + result.getHttpStatusCode());
}
```

## Send SMS to Multiple Recipients

```java
import com.azure.communication.sms.models.SmsSendOptions;
import java.util.Arrays;
import java.util.List;

List<String> recipients = Arrays.asList(
    "+14255551111",
    "+14255552222",
    "+14255553333"
);

// With options
SmsSendOptions options = new SmsSendOptions()
    .setDeliveryReportEnabled(true)
    .setTag("marketing-campaign-001");

Iterable<SmsSendResult> results = smsClient.sendWithResponse(
    "+14255550100",      // From
    recipients,          // To list
    "Flash sale! 50% off today only.",
    options,
    Context.NONE
).getValue();

for (SmsSendResult result : results) {
    if (result.isSuccessful()) {
        System.out.println("Sent to " + result.getTo() + ": " + result.getMessageId());
    } else {
        System.out.println("Failed to " + result.getTo() + ": " + result.getErrorMessage());
    }
}
```

## Send Options

```java
SmsSendOptions options = new SmsSendOptions();

// Enable delivery reports (sent via Event Grid)
options.setDeliveryReportEnabled(true);

// Add custom tag for tracking
options.setTag("order-confirmation-12345");
```

## Response Handling

```java
import com.azure.core.http.rest.Response;

Response<Iterable<SmsSendResult>> response = smsClient.sendWithResponse(
    "+14255550100",
    Arrays.asList("+14255551234"),
    "Hello!",
    new SmsSendOptions().setDeliveryReportEnabled(true),
    Context.NONE
);

// Check HTTP response
System.out.println("Status code: " + response.getStatusCode());
System.out.println("Headers: " + response.getHeaders());

// Process results
for (SmsSendResult result : response.getValue()) {
    System.out.println("Message ID: " + result.getMessageId());
    System.out.println("Successful: " + result.isSuccessful());
    
    if (!result.isSuccessful()) {
        System.out.println("HTTP Status: " + result.getHttpStatusCode());
        System.out.println("Error: " + result.getErrorMessage());
    }
}
```

## Async Operations

```java
import reactor.core.publisher.Mono;

SmsAsyncClient asyncClient = new SmsClientBuilder()
    .connectionString("<connection-string>")
    .buildAsyncClient();

// Send single message
asyncClient.send("+14255550100", "+14255551234", "Async message!")
    .subscribe(
        result -> System.out.println("Sent: " + result.getMessageId()),
        error -> System.out.println("Error: " + error.getMessage())
    );

// Send to multiple with options
SmsSendOptions options = new SmsSendOptions()
    .setDeliveryReportEnabled(true);

asyncClient.sendWithResponse(
    "+14255550100",
    Arrays.asList("+14255551111", "+14255552222"),
    "Bulk async message",
    options)
    .subscribe(response -> {
        for (SmsSendResult result : response.getValue()) {
            System.out.println("Result: " + result.getTo() + " - " + result.isSuccessful());
        }
    });
```

## Error Handling

```java
import com.azure.core.exception.HttpResponseException;

try {
    SmsSendResult result = smsClient.send(
        "+14255550100",
        "+14255551234",
        "Test message"
    );
    
    // Individual message errors don't throw exceptions
    if (!result.isSuccessful()) {
        handleMessageError(result);
    }
    
} catch (HttpResponseException e) {
    // Request-level failures (auth, network, etc.)
    System.out.println("Request failed: " + e.getMessage());
    System.out.println("Status: " + e.getResponse().getStatusCode());
} catch (RuntimeException e) {
    System.out.println("Unexpected error: " + e.getMessage());
}

private void handleMessageError(SmsSendResult result) {
    int status = result.getHttpStatusCode();
    String error = result.getErrorMessage();
    
    if (status == 400) {
        System.out.println("Invalid phone number: " + result.getTo());
    } else if (status == 429) {
        System.out.println("Rate limited - retry later");
    } else {
        System.out.println("Error " + status + ": " + error);
    }
}
```

## Delivery Reports

Delivery reports are sent via Azure Event Grid. Configure an Event Grid subscription for your ACS resource.

```java
// Event Grid webhook handler (in your endpoint)
public void handleDeliveryReport(String eventJson) {
    // Parse Event Grid event
    // Event type: Microsoft.Communication.SMSDeliveryReportReceived
    
    // Event data contains:
    // - messageId: correlates to SmsSendResult.getMessageId()
    // - from: sender number
    // - to: recipient number
    // - deliveryStatus: "Delivered", "Failed", etc.
    // - deliveryStatusDetails: detailed status
    // - receivedTimestamp: when status was received
    // - tag: your custom tag from SmsSendOptions
}
```

## SmsSendResult Properties

| Property | Type | Description |
|----------|------|-------------|
| `getMessageId()` | String | Unique message identifier |
| `getTo()` | String | Recipient phone number |
| `isSuccessful()` | boolean | Whether send succeeded |
| `getHttpStatusCode()` | int | HTTP status for this recipient |
| `getErrorMessage()` | String | Error details if failed |
| `getRepeatabilityResult()` | RepeatabilityResult | Idempotency result |

## Environment Variables

```bash
AZURE_COMMUNICATION_ENDPOINT=https://<resource>.communication.azure.com  # Required for all auth methods
AZURE_COMMUNICATION_CONNECTION_STRING=endpoint=https://...;accesskey=...  # Alternative to Entra ID auth
SMS_FROM_NUMBER=+14255550100  # Required for the sender phone number
AZURE_TOKEN_CREDENTIALS=prod  # Required only if DefaultAzureCredential is used in production
```

## Best Practices

1. **Phone Number Format** - Use E.164 format: `+[country code][number]`
2. **Delivery Reports** - Enable for critical messages (OTP, alerts)
3. **Tagging** - Use tags to correlate messages with business context
4. **Error Handling** - Check `isSuccessful()` for each recipient individually
5. **Rate Limiting** - Implement retry with backoff for 429 responses
6. **Bulk Sending** - Use batch send for multiple recipients (more efficient)

## Trigger Phrases

- "send SMS Java", "text message Java"
- "SMS notification", "OTP SMS", "bulk SMS"
- "delivery report SMS", "Azure Communication Services SMS"

Все файлы

0 файлов

Установить azure-communication-sms-java

Скачайте файлы навыков и распакуйте их в каталог .claude/skills/.

Скачать ZIP

Клонируйте репозиторий и скопируйте файлы навыка в свой проект.

git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-java/skills/azure-communication-sms-java # Copy SKILL.md to your .claude/skills/ directory

Копировать Копировать
Быстрая настройка: Скопируйте папку со скиллом в каталог .claude/skills/ Claude автоматически обнаружит и начнет использовать этот скилл
Репозиторий microsoft/skills

Похожие навыки

brightdata-cli
Обновлено время 29 июня 2026 г.
agentwallet
Обновлено время 7 июля 2026 г.
humanize
Обновлено время 7 июля 2026 г.
korean-stock-search
Обновлено время 8 июля 2026 г.
OR