use tencentcloud_sms_sdk::{
Client, ClientProfile, Credential, HttpProfile, SendSmsRequest, TencentCloudError,
};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
env_logger::init();
println!("TencentCloud SMS SDK Example - Send SMS");
println!("=====================================");
println!("\n1. Basic SMS sending:");
basic_send_sms().await?;
println!("\n2. SMS sending with custom configuration:");
send_sms_with_config().await?;
println!("\n3. International SMS sending:");
send_international_sms().await?;
println!("\n4. Error handling:");
handle_errors().await?;
Ok(())
}
async fn basic_send_sms() -> Result<(), Box<dyn std::error::Error>> {
let credential =
Credential::from_env().map_err(|e| format!("Failed to load credentials: {}", e))?;
let client = Client::new(credential, "ap-guangzhou");
let request = SendSmsRequest::new(
vec!["+8613800000000".to_string()], "1400000000", "123456", "YourSignature", vec!["123456".to_string()], );
if let Err(e) = request.validate() {
println!("Request validation failed: {}", e);
return Ok(());
}
match client.send_sms(request).await {
Ok(response) => {
println!("SMS sent successfully!");
println!("Request ID: {}", response.request_id);
println!("Total messages: {}", response.send_status_set.len());
println!("Successful: {}", response.success_count());
println!("Failed: {}", response.failed_count());
println!("Total fee: {}", response.get_total_fee());
for status in &response.send_status_set {
println!(
"Phone: {}, Status: {}, Message: {}",
status.phone_number, status.code, status.message
);
}
}
Err(e) => {
println!("Failed to send SMS: {}", e.print_all());
}
}
Ok(())
}
async fn send_sms_with_config() -> Result<(), Box<dyn std::error::Error>> {
let credential =
Credential::from_env().map_err(|e| format!("Failed to load credentials: {}", e))?;
let mut http_profile = HttpProfile::new();
http_profile
.set_req_timeout(30)
.set_connect_timeout(30)
.set_keep_alive(true);
let mut client_profile = ClientProfile::with_http_profile(http_profile);
client_profile.set_debug(true);
let client = Client::with_profile(credential, "ap-guangzhou", client_profile);
let mut request = SendSmsRequest::new(
vec!["+8613800000000".to_string()],
"1400000000",
"123456",
"YourSignature",
vec!["123456".to_string()],
);
request
.set_session_context("example_session_123")
.set_extend_code("01");
match client.send_sms(request).await {
Ok(response) => {
println!("SMS sent with custom config!");
println!("Request ID: {}", response.request_id);
for phone in &["+8613800000000"] {
if response.check_phone_success(phone) {
println!("✓ {} - Success", phone);
} else {
println!("✗ {} - Failed", phone);
}
}
}
Err(e) => {
println!("Failed to send SMS: {}", e.print_all());
}
}
Ok(())
}
async fn send_international_sms() -> Result<(), Box<dyn std::error::Error>> {
let credential =
Credential::from_env().map_err(|e| format!("Failed to load credentials: {}", e))?;
let client = Client::new(credential, "ap-guangzhou");
let request = SendSmsRequest::new_international(
vec!["+1234567890".to_string()], "1400000000", "123456", vec!["123456".to_string()], );
match client.send_sms(request).await {
Ok(response) => {
println!("International SMS sent successfully!");
println!("Request ID: {}", response.request_id);
for status in &response.send_status_set {
println!(
"Phone: {}, Country: {}, Status: {}, Fee: {}",
status.phone_number, status.iso_code, status.code, status.fee
);
}
}
Err(e) => {
println!("Failed to send international SMS: {}", e.print_all());
}
}
Ok(())
}
async fn handle_errors() -> Result<(), Box<dyn std::error::Error>> {
let credential = Credential::new("invalid_id", "invalid_key", None);
let client = Client::new(credential, "ap-guangzhou");
let request = SendSmsRequest::new(
vec!["+8613800000000".to_string()],
"1400000000",
"123456",
"YourSignature",
vec!["123456".to_string()],
);
match client.send_sms(request).await {
Ok(_) => {
println!("Unexpected success with invalid credentials");
}
Err(e) => {
println!("Expected error occurred:");
println!("Error type: {}", e);
println!("Error details: {}", e.print_all());
if e.is_network_error() {
println!("This is a network error");
} else if let Some(code) = e.code() {
println!("API error code: {}", code);
match code {
"UnauthorizedOperation.SmsSdkAppIdVerifyFail" => {
println!("Solution: Check your SMS SDK App ID");
}
"FailedOperation.SignatureIncorrectOrUnapproved" => {
println!("Solution: Check your SMS signature");
}
"FailedOperation.TemplateIncorrectOrUnapproved" => {
println!("Solution: Check your SMS template");
}
_ => {
println!("Unknown error code: {}", code);
}
}
}
}
}
Ok(())
}
#[allow(dead_code)]
async fn send_sms_batch() -> Result<(), Box<dyn std::error::Error>> {
let credential = Credential::from_env()?;
let client = Client::new(credential, "ap-guangzhou");
let phone_numbers = vec![
"+8613800000000".to_string(),
"+8613800000001".to_string(),
"+8613800000002".to_string(),
];
let request = SendSmsRequest::new(
phone_numbers,
"1400000000",
"123456",
"YourSignature",
vec!["123456".to_string()],
);
match client.send_sms(request).await {
Ok(response) => {
println!("Batch SMS Results:");
println!("Total: {}", response.send_status_set.len());
println!("Success: {}", response.success_count());
println!("Failed: {}", response.failed_count());
let successful_numbers = response.get_successful_numbers();
if !successful_numbers.is_empty() {
println!("Successful numbers: {:?}", successful_numbers);
}
let failed_numbers = response.get_failed_numbers();
if !failed_numbers.is_empty() {
println!("Failed numbers:");
for (phone, reason) in failed_numbers {
println!(" {} - {}", phone, reason);
}
}
}
Err(e) => {
println!("Batch SMS failed: {}", e.print_all());
}
}
Ok(())
}