DEV Community

Narcis Bodea for SMSTunnel

Posted on Originally published at smstunnel.io Fully Autonomous

Keep your Twilio code, send the texts from your own Android phone

Some texts don't need a rented number. "Your table is ready", a reminder from a small clinic, a sign-in code for the twelve people who use your internal tool: these read better coming from a number people already know, and when someone answers, the reply should land on a real phone.

You can keep your Twilio code for those. SMSTunnel has a Twilio-compatible API: Twilio's own helper libraries talk to it once you change the address and the credential, and an Android phone you own sends each text from its SIM.

This isn't a Twilio replacement. Here's where each one fits, then the code.

Which texts go where

Keep on Twilio: high volume, short codes, toll-free numbers, sender names, MMS, voice, and US business traffic that needs A2P 10DLC.

Send from your own phone:

  • one-to-one texts where the reply should reach you;
  • countries where your SIM plan costs less than an API route;
  • development and testing: the texts really arrive, and the free plan covers 25 a day.

The limits, plainly:

  • Android limits an app to about 30 SMS parts a minute, so SMSTunnel sends at most 28 parts every 65 seconds from one phone.
  • The phone has to be online. If it isn't, the text waits, for up to 3 days.
  • Texts go out as ordinary texts from your phone, under the terms of your mobile plan.
  • There are no delivery reports yet. A text that went out stays at sent, so if your code waits for delivered, treat sent as done.

What you need

  • An Android phone with a SIM and the free SMSTunnel app.
  • An API key: in the dashboard, open Apps → Add an app → Already use Twilio?. It shows your Account SID too.

The key takes the place of your Auth Token:

export TWILIO_ACCOUNT_SID="AC..."
export SMSTUNNEL_API_KEY="sk_live_..."
Enter fullscreen mode Exit fullscreen mode

1. Change two things

Node.js (twilio 6.3.1):

import twilio from 'twilio';

const client = twilio(process.env.TWILIO_ACCOUNT_SID, process.env.SMSTUNNEL_API_KEY);
client.api.baseUrl = 'https://api.smstunnel.io';

const message = await client.messages.create({
  to: '+15558675310',
  body: 'Your order has shipped.',
});
console.log(message.sid, message.status); // SM…, queued

// Later: the text's status
const latest = await client.messages(message.sid).fetch();
console.log(latest.status); // sent or failed
Enter fullscreen mode Exit fullscreen mode

Python (twilio 9.13.0):

import os
from twilio.rest import Client

client = Client(os.environ["TWILIO_ACCOUNT_SID"], os.environ["SMSTUNNEL_API_KEY"])
client.api.base_url = "https://api.smstunnel.io"

message = client.messages.create(to="+15558675310", body="Your order has shipped.")
print(message.sid, message.status)  # SM…, queued

# Later: the text's status
print(client.messages(message.sid).fetch().status)  # sent or failed
Enter fullscreen mode Exit fullscreen mode

You don't need a From: the text leaves from the phone's own number.

PHP, Ruby, C#, Java and Go work too, with a small HTTP-client hook that swaps the host. All seven are in the guide, each run against the library's current version.

2. Status callbacks

Add a StatusCallback as you would for Twilio, on an https address:

curl -X POST "https://api.smstunnel.io/2010-04-01/Accounts/$TWILIO_ACCOUNT_SID/Messages.json" \
  --data-urlencode "To=+15558675310" \
  --data-urlencode "Body=Your order has shipped." \
  --data-urlencode "StatusCallback=https://example.com/sms/status" \
  -u "$TWILIO_ACCOUNT_SID:$SMSTUNNEL_API_KEY"
Enter fullscreen mode Exit fullscreen mode

Your address gets Twilio's form fields (MessageSid, MessageStatus, To…), signed with X-Twilio-Signature.

Check that signature before you act on a request, as you would with Twilio. SMSTunnel stores API keys only as hashes, so it can't sign with one: your account has a separate signing key under Apps → Twilio. If your code already validates with the same token it sends with, choose Use my own value and paste that SMSTunnel key. Your existing validateRequest call then works unchanged.

3. Replies, in Twilio's format

Turn on Sync received texts in the phone app. In the dashboard, open Apps → Forward received texts, save your address and pick the Twilio format. Your webhook gets the fields it gets from Twilio, and a TwiML <Message> answer sends one reply from the same phone and SIM:

import http from 'node:http';
import twilio from 'twilio';

// Apps → Twilio in your SMSTunnel dashboard: the signing key.
const SIGNING_KEY = process.env.TWILIO_SIGNING_KEY;
// Your address exactly as saved in Forward received texts.
const ADDRESS = process.env.FORWARDING_URL ?? 'https://example.com/sms';

http.createServer((req, res) => {
  let body = '';
  req.on('data', (chunk) => (body += chunk));
  req.on('end', () => {
    const params = Object.fromEntries(new URLSearchParams(body));
    if (!twilio.validateRequest(SIGNING_KEY, req.headers['x-twilio-signature'] ?? '', ADDRESS, params)) {
      res.writeHead(403).end();
      return;
    }
    console.log(`From ${params.From}: ${params.Body}`);

    // One reply to the sender, from the phone that received the text.
    const twiml = new twilio.twiml.MessagingResponse();
    twiml.message(`Thanks, we got your text: ${params.Body}`);
    res.writeHead(200, { 'Content-Type': 'text/xml' }).end(twiml.toString());
  });
}).listen(3000);
Enter fullscreen mode Exit fullscreen mode

Automatic replies have limits on purpose: one per received text, 10 an hour to one sender, 500 a day per account, and never to sender names, short codes or premium-rate numbers.

4. Verify codes

Twilio Verify calls work the same way. Your Service SID can stay as it is:

import twilio from 'twilio';

const client = twilio(process.env.TWILIO_ACCOUNT_SID, process.env.SMSTUNNEL_API_KEY);
client.verify.baseUrl = 'https://api.smstunnel.io';

// Your Verify Service SID (VA…) works as it is.
const service = client.verify.v2.services(process.env.TWILIO_VERIFY_SERVICE_SID);
const [to, code] = process.argv.slice(2);

if (!code) {
  // node verify.mjs +15558675310: texts a code to the number
  const verification = await service.verifications.create({ to, channel: 'sms' });
  console.log(verification.status); // pending
} else {
  // node verify.mjs +15558675310 123456: checks the code the person typed
  const check = await service.verificationChecks.create({ to, code });
  console.log(check.status); // approved when the code is right, else pending
}
Enter fullscreen mode Exit fullscreen mode

SMS is the only channel. A code lasts 10 minutes, with up to 5 sends and 5 checks. The Verify guide has this for all seven libraries, plus what isn't supported.

5. Use both

Two clients from the same library, and one small function that picks the path:

import twilio from 'twilio';

// Twilio, as today: your Account SID, Auth Token and Twilio number.
const viaTwilio = twilio(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);

// Your own phone, through SMSTunnel: the same library, another address and key.
const viaPhone = twilio(process.env.TWILIO_ACCOUNT_SID, process.env.SMSTUNNEL_API_KEY);
viaPhone.api.baseUrl = 'https://api.smstunnel.io';

// Countries your own SIM texts at your plan's rates (an example: put yours).
const PHONE_COUNTRIES = ['+44'];

// One text to one number. A text that expects a reply goes from your phone,
// so the reply reaches you.
export function sendText({ to, body, expectsReply = false }) {
  const fromPhone = expectsReply || PHONE_COUNTRIES.some((code) => to.startsWith(code));
  const client = fromPhone ? viaPhone : viaTwilio;
  return client.messages.create({ to, body, from: process.env.TWILIO_PHONE_NUMBER });
}
Enter fullscreen mode Exit fullscreen mode

What else is different

  • One number per request, and no MMS.
  • SendAt is refused with an error, so a reminder meant for tomorrow can't go out today by mistake.
  • price is null: you pay your SMSTunnel plan and your mobile plan, nothing per text.
  • A received text has an empty To, because SMSTunnel doesn't know your phone's own number.

The full list, the error codes and every library are in the guide.


Twilio is a trademark of Twilio Inc. SMSTunnel is not affiliated with Twilio.

Disclosure: I build SMSTunnel. This post was written with AI from the official setup guide linked above.

Top comments (0)