opção
LarLar Skill Desenvolvimento de APIs azure-communication-sms-java

azure-communication-sms-java

microsoft/skills microsoft/skills

Envie mensagens SMS para um ou vários destinatários com relatório de entrega usando o SDK Java do Azure Communication Services para SMS.

...Expandir tudo
1
Tempo atualizado 14 de Setembro de 2026

SMS do Azure Communication (Java)

Envie mensagens SMS para um ou vários destinatários com relatório de entrega.

Instalação


    com.azure
    azure-communication-sms
    1.2.0

Criação do cliente

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;

// Desenvolvimento local: DefaultAzureCredential. Produção: defina AZURE_TOKEN_CREDENTIALS=prod ou AZURE_TOKEN_CREDENTIALS=
TokenCredential credential = new DefaultAzureCredentialBuilder()
    .requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
    .build();
// Ou use uma credencial específica diretamente em produção:
// Consulte https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();

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

// Com string de conexão
SmsClient smsClient = new SmsClientBuilder()
    .connectionString("")
    .buildClient();

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

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

// Cliente assíncrono
SmsAsyncClient smsAsyncClient = new SmsClientBuilder()
    .connectionString("")
    .buildAsyncClient();

Enviar SMS para um único destinatário

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

// Envio simples
SmsSendResult result = smsClient.send(
    "+14255550100",      // De (seu número de telefone ACS)
    "+14255551234",      // Para
    "Seu código de verificação é 123456");

System.out.println("ID da mensagem: " + result.getMessageId());
System.out.println("Para: " + result.getTo());
System.out.println("Sucesso: " + result.isSuccessful());

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

Enviar SMS para vários destinatários

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

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

// Com opções
SmsSendOptions options = new SmsSendOptions()
    .setDeliveryReportEnabled(true)
    .setTag("marketing-campaign-001");

Iterable results = smsClient.sendWithResponse(
    "+14255550100",      // De
    recipients,          // Para a lista
    "Promoção relâmpago! 50% de desconto só hoje.",
    options,
    Context.NONE
).getValue();

for (SmsSendResult result : results) {
    if (result.isSuccessful()) {
        System.out.println("Enviado para " + result.getTo() + ": " + result.getMessageId());
    } else {
        System.out.println("Falha ao enviar para " + result.getTo() + ": " + result.getErrorMessage());
    }
}

Opções de envio

SmsSendOptions options = new SmsSendOptions();

// Habilitar relatórios de entrega (enviados via Event Grid)
options.setDeliveryReportEnabled(true);

// Adicionar tag personalizada para rastreamento
options.setTag("order-confirmation-12345");

Tratamento de respostas

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

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

// Verificar resposta HTTP
System.out.println("Código de status: " + response.getStatusCode());
System.out.println("Cabeçalhos: " + response.getHeaders());

// Processar resultados
for (SmsSendResult result : response.getValue()) {
    System.out.println("ID da mensagem: " + result.getMessageId());
    System.out.println("Bem-sucedido: " + result.isSuccessful());
    
    if (!result.isSuccessful()) {
        System.out.println("Status HTTP: " + result.getHttpStatusCode());
        System.out.println("Erro: " + result.getErrorMessage());
    }
}

Operações assíncronas

import reactor.core.publisher.Mono;

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

// Enviar uma única mensagem
asyncClient.send("+14255550100", "+14255551234", "Mensagem assíncrona!")
    .subscribe(
        result -> System.out.println("Enviado: " + result.getMessageId()),
        error -> System.out.println("Erro: " + error.getMessage())
    );

// Enviar para vários destinatários com opções
SmsSendOptions options = new SmsSendOptions()
    .setDeliveryReportEnabled(true);

asyncClient.sendWithResponse(
    "+14255550100",
    Arrays.asList("+14255551111", "+14255552222"),
    "Mensagem em massa assíncrona",
    options)
    .subscribe(response -> {
        for (SmsSendResult result : response.getValue()) {
            System.out.println("Resultado: " + result.getTo() + " - " + result.isSuccessful());
        }
    });

Tratamento de erros

import com.azure.core.exception.HttpResponseException;

try {
    SmsSendResult result = smsClient.send(
        "+14255550100",
        "+14255551234",
        "Mensagem de teste"
    );
    
    // Erros em mensagens individuais não lançam exceções
    if (!result.isSuccessful()) {
        handleMessageError(result);
    }
    
} catch (HttpResponseException e) {
    // Falhas no nível da solicitação (autenticação, rede, etc.)
    System.out.println("Falha na solicitação: " + e.getMessage());
    System.out.println("Status: " + e.getResponse().getStatusCode());
} catch (RuntimeException e) {
    System.out.println("Erro inesperado: " + e.getMessage());
}

private void handleMessageError(SmsSendResult result) {
    int status = result.getHttpStatusCode();
    String error = result.getErrorMessage();
    
    if (status == 400) {
        System.out.println("Número de telefone inválido: " + result.getTo());
    } else if (status == 429) {
        System.out.println("Limite de envios atingido — tente novamente mais tarde");
    } else {
        System.out.println("Erro " + status + ": " + error);
    }
}

Relatórios de entrega

Os relatórios de entrega são enviados por meio do Azure Event Grid. Configure uma assinatura do Event Grid para seu recurso ACS.

// Manipulador de webhook do Event Grid (em seu endpoint)
public void handleDeliveryReport(String eventJson) {
    // Analise o evento do Event Grid
    // Tipo de evento: Microsoft.Communication.SMSDeliveryReportReceived
    
    // Os dados do evento contêm:
    // - messageId: corresponde a SmsSendResult.getMessageId()
    // - from: número do remetente
    // - to: número do destinatário
    // - deliveryStatus: “Entregue”, “Falha”, etc.
    // - deliveryStatusDetails: status detalhado
    // - receivedTimestamp: quando o status foi recebido
    // - tag: sua tag personalizada de SmsSendOptions
}

Propriedades de SmsSendResult

Propriedade Tipo Descrição
getMessageId() String Identificador único da mensagem
getTo() String Número de telefone do destinatário
isSuccessful() booleano Se o envio foi bem-sucedido
getHttpStatusCode() int Código de status HTTP para este destinatário
getErrorMessage() String Detalhes do erro em caso de falha
getRepeatabilityResult() RepeatabilityResult Resultado da idempotência

Variáveis de ambiente

AZURE_COMMUNICATION_ENDPOINT=https://.communication.azure.com  # Obrigatório para todos os métodos de autenticação
AZURE_COMMUNICATION_CONNECTION_STRING=endpoint=https://...;accesskey=...  # Alternativa à autenticação com Entra ID
SMS_FROM_NUMBER=+14255550100  # Obrigatório para o número de telefone do remetente
AZURE_TOKEN_CREDENTIALS=prod  # Obrigatório apenas se DefaultAzureCredential for usado em produção

Práticas recomendadas

  1. Formato do número de telefone – Use o formato E.164: +[código do país][número]
  2. Relatórios de entrega — Ative para mensagens críticas (OTP, alertas)
  3. Etiquetagem — Use etiquetas para correlacionar mensagens com o contexto de negócios
  4. Tratamento de erros — Verifique isSuccessful() para cada destinatário individualmente
  5. Limitação de taxa — Implemente tentativas repetidas com intervalo de espera para respostas 429
  6. Envio em massa – Use o envio em lote para vários destinatários (mais eficiente)

Frases de acionamento

  • “enviar SMS em Java”, “mensagem de texto em Java”
  • “notificação por SMS”, “SMS com OTP”, “SMS em massa”
  • “relatório de entrega por SMS”, “SMS do Azure Communication Services”
Ver no 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"

Todos os arquivos

0 arquivos

Instalar azure-communication-sms-java

Baixe e descompacte os arquivos de habilidades no diretório .claude/skills/.

Baixar ZIP

Clone o repositório e copie os arquivos da habilidade para o seu projeto.

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

Copiar Copiar
Configuração rápida: Copie a pasta da habilidade para .claude/skills/ O Claude detectará e utilizará automaticamente a habilidade
Repositório microsoft/skills

Habilidades relacionadas

brightdata-cli
Tempo atualizado 29 de Junho de 2026
agentwallet
Tempo atualizado 7 de Julho de 2026
humanize
Tempo atualizado 7 de Julho de 2026
korean-stock-search
Tempo atualizado 8 de Julho de 2026
OR