azure-communication-sms-java
microsoft/skills
Azure Communication Services SMS Java SDK를 사용하여 전달 상태 보고 기능을 통해 한 명 또는 여러 명의 수신자에게 SMS 메시지를 전송할 수 있습니다.
...모든 것을 확장하십시오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("메시지 ID: " + 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("메시지 ID: " + 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", "Async message!")
.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를 통해 전송됩니다. ACS 리소스에 대한 Event Grid 구독을 구성하십시오.
// 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() |
boolean | 전송 성공 여부 |
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을 사용하는 경우에만 필수
모범 사례
- 전화번호 형식 - E.164 형식 사용:
+[국가 코드][번호] - 전달 보고서 - 중요 메시지(OTP, 알림)의 경우 활성화
- 태깅 - 태그를 사용하여 메시지를 비즈니스 컨텍스트와 연관시키세요
- 오류 처리 - 각 수신자에 대해 개별적으로
isSuccessful()을확인하십시오 - 속도 제한 - 429 응답 시 백오프를 적용한 재시도 구현
- 일괄 전송 - 수신자가 여러 명일 경우 일괄 전송을 사용하세요(더 효율적)
트리거 문구
- "Java로 SMS 보내기", "Java 문자 메시지"
- "SMS 알림", "OTP SMS", "대량 SMS"
- "전송 확인 SMS", "Azure Communication Services SMS"
---
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
복사





집
