send a message via twilio sms in rust

To send a message via Twilio SMS API in Rust, you will need to use an HTTP client library to make requests to Twilio's REST API.

One popular HTTP client library in Rust is reqwest. You can add it to your project by adding the following line to your Cargo.toml:

main.rs
[dependencies]
reqwest = { version = "0.11", features = ["blocking", "json"] }
79 chars
3 lines

Here's an example code snippet that shows how to use reqwest to send a SMS message via the Twilio API:

main.rs
use std::collections::HashMap;

const ACCOUNT_SID: &str = "your_account_sid";
const AUTH_TOKEN: &str = "your_auth_token";

fn send_sms(to_phone_number: &str, from_phone_number: &str, message: &str) -> Result<(), Box<dyn std::error::Error>> {
    let client = reqwest::blocking::Client::new();

    let mut params = HashMap::new();
    params.insert("To", to_phone_number);
    params.insert("From", from_phone_number);
    params.insert("Body", message);

    let res = client
        .post(format!("https://api.twilio.com/2010-04-01/Accounts/{}/Messages.json", ACCOUNT_SID))
        .form(&params)
        .basic_auth(ACCOUNT_SID, Some(AUTH_TOKEN))
        .send()?;

    println!("status: {:?}", res.status());
    println!("body: {:?}", res.text()?);
    Ok(())
}

fn main() {
    let to_phone_number = "+1234567890";
    let from_phone_number = "+9876543210";
    let message = "Hello from Rust!";

    send_sms(to_phone_number, from_phone_number, message).unwrap();
}
973 chars
32 lines

Make sure to replace the ACCOUNT_SID and AUTH_TOKEN constants with your actual Twilio account credentials. Also, replace the to_phone_number and from_phone_number variables with the phone numbers you want to use (make sure to include the country code). Finally, replace message variable with the actual message you want to send.

This code will make a POST request to Twilio's API, passing the To, From, and Body parameters in the request body. Twilio will then handle the message sending process on your behalf.

related categories

gistlibby LogSnag