SMSNET
Guide

Send SMS From Java Without a Twilio Account

To send an SMS from Java you make one authenticated HTTP request. With SMSNET that request makes your own Android phone send the text, so there is no provider account and no number to rent.

What do I need before the first call?

Two things: a connected phone and an API key. Install the SMSNET Gateway app on any Android 8.0 or newer phone with a SIM, sign in, and the last screen of setup shows your key once. The Android gateway guide shows every screen. Put the key in an environment variable or Spring config; it can be rotated from the Developers page if it ever leaks.

The free plan is enough to build against: 300 messages a month, 20 a day, and replies are never counted. Recipients go in E.164 format (+15551234567), and the person you are texting should have agreed to hear from you.

How do I send an SMS with Spring Boot RestClient?

Spring Boot 3.2+ includes RestClient, a modern, fluent HTTP client.

package com.example.sms;

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class SmsService {

    private final RestClient restClient;

    public SmsService(@Value("${smsnet.api.key}") String apiKey) {
        this.restClient = RestClient.builder()
            .baseUrl("https://smsnet.net/api/v1")
            .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
            .defaultHeader("X-API-Key", apiKey)
            .build();
    }

    public record SendResult(
        boolean ok,
        String message_id,
        String conversation_id,
        String device_id,
        Quota quota
    ) {}

    public record Quota(
        Monthly month,
        Daily day
    ) {}

    public record Monthly(long used, long limit) {}
    public record Daily(long used, long limit) {}

    public SendResult send(String to, String body, boolean transactional) {
        Map<String, Object> payload = Map.of(
            "to", to,
            "body", body,
            "transactional", transactional
        );
        return restClient.post()
            .uri("/messages/send")
            .body(payload)
            .retrieve()
            .body(SendResult.class);
    }
}

Configure the key in application.yml:

smsnet:
  api:
    key: ${SMSNET_API_KEY:}

A successful response looks like this:

{
  "ok": true,
  "message_id": "msg_01j9x8k2...",
  "conversation_id": "conv_01j9x8k2...",
  "device_id": "dev_01j9x8k2...",
  "quota": {
    "month": { "used": 13, "limit": 300 },
    "day": { "used": 4, "limit": 20 }
  }
}

quota is there so your app can slow down before it hits the wall instead of discovering it as a 429. The limit has a fifth of headroom above it; once you are in that band the response carries "grace": true and a note.

Set transactional=true only for a message the recipient is waiting on right now, such as a login code. It skips the queue's pacing gap and quiet hours and reaches the phone in about a second, while still respecting the daily ceiling and the warmup ramp on a new line.

How do I send an SMS with java.net.http.HttpClient (no Spring)?

For a plain Java 11+ project without Spring:

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import com.fasterxml.jackson.databind.ObjectMapper;

public class SmsClient {
    private static final String API_URL = "https://smsnet.net/api/v1/messages/send";
    private static final HttpClient HTTP = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(15))
        .build();
    private static final ObjectMapper JSON = new ObjectMapper();

    public static void send(String to, String body, boolean transactional) throws Exception {
        String apiKey = System.getenv("SMSNET_API_KEY");
        if (apiKey == null || apiKey.isBlank()) throw new IllegalStateException("SMSNET_API_KEY not set");

        var payload = Map.of("to", to, "body", body, "transactional", transactional);
        String json = JSON.writeValueAsString(payload);

        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(API_URL))
            .header("X-API-Key", apiKey)
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(json, StandardCharsets.UTF_8))
            .build();

        HttpResponse<String> response = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() >= 400) {
            throw new RuntimeException("SMSNET " + response.statusCode() + ": " + response.body());
        }
        System.out.println("Sent: " + response.body());
    }
}

Add Jackson dependency (Maven):

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.17.0</version>
</dependency>

How do I read replies in Java?

Two options. Polling needs no public URL and suits a batch job; a webhook suits a server.

Polling uses the message feed with a cursor. The first call without since returns the latest messages; every call after that passes back next_cursor, so nothing is missed or repeated even when several messages share a millisecond.

// Polling example (Spring RestClient)
public record MessagePage(
    List<Message> messages,
    String next_cursor,
    boolean has_more
) {}

public record Message(
    String from_number,
    String body,
    String conversation_id
) {}

public MessagePage pollInbound(String since) {
    return restClient.get()
        .uri(uri -> uri.path("/messages")
            .queryParam("direction", "inbound")
            .queryParam("limit", 100)
            .queryParamIfPresent("since", Optional.ofNullable(since))
            .build())
        .retrieve()
        .body(MessagePage.class);
}

For a webhook, register your HTTPS endpoint once (PUT /api/v1/webhooks with {"url": "..."}) and keep the secret from the response. SMSNET then POSTs message.received and message.status events, signs each one, and retries nine times over about three days if your endpoint is down. Verify the signature before trusting anything:

@Controller
public class SmsWebhookController {

    @Value("${smsnet.webhook.secret}")
    private String secret;

    @PostMapping("/sms/webhook")
    public ResponseEntity<Void> webhook(
        @RequestHeader("X-SMSNET-Timestamp") String ts,
        @RequestHeader("X-SMSNET-Signature") sig,
        @RequestHeader("X-SMSNET-Delivery") String delivery,
        @RequestBody String rawBody
    ) {
        if (ts == null || sig == null) return ResponseEntity.badRequest().build();
        if (Math.abs(Instant.now().getEpochSecond() - Long.parseLong(ts)) > 300) {
            return ResponseEntity.badRequest().build();
        }

        String expected = "v1=" + HmacSHA256(secret, ts + "." + rawBody);
        if (!MessageDigest.isEqual(expected.getBytes(), sig.getBytes())) {
            return ResponseEntity.badRequest().build();
        }

        // Dedupe on delivery ID (store in Redis, DB, or in-memory for demo)
        // ...

        // Parse event
        JsonNode event = new ObjectMapper().readTree(rawBody);
        if ("message.received".equals(event.get("event").asText())) {
            String from = event.get("data").get("from").asText();
            String body = event.get("data").get("body").asText();
            System.out.println("Reply from " + from + ": " + body);
        } else if ("message.status".equals(event.get("event").asText())) {
            String msgId = event.get("data").get("message_id").asText();
            String status = event.get("data").get("status").asText();
            System.out.println(msgId + " is now " + status);
        }
        return ResponseEntity.ok().build();
    }

    private String HmacSHA256(String secret, String data) {
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
            return HexFormat.of().formatHex(hash);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

The signed material is the timestamp, a dot, and the raw request body, so verify against rawBody before anything parses it. Dedupe on the X-SMSNET-Delivery header, which is stable across retries. Send yourself a test event with POST /api/v1/webhooks/test before any real traffic exists.

What errors should the script expect?

StatusWhenWhat to do
400Missing to or body, or no phone connected to the accountFix the request, or connect a phone
401Missing or wrong key; the error says whether the key was rotatedLoad the key from the environment, rotate if needed
403The recipient opted out; the error names the date and the words they usedDo not retry; remove them from your list
429Monthly or daily allowance reached, including the headroomWait for the window, or upgrade the plan

Everything in this guide runs on the free plan. For the full endpoint list, including conversations, contacts and campaigns, see What Is an SMS API and How to Use One. If you would rather have an AI agent do the calling, the MCP server guide exposes the same operations as tools.

FAQ

How do I send an SMS from a Java application?

POST JSON with to and body to https://smsnet.net/api/v1/messages/send, with your SMSNET API key in the X-API-Key header. The response returns a message_id and your remaining quota, and the message is sent from the Android phone connected to your account. Spring Boot RestClient or java.net.http.HttpClient both work.

Do I need Twilio or a carrier account to send SMS from Java?

No. SMSNET uses an Android phone and SIM you already own as the sender, so there is no carrier account and no number rental; you text from your own number on your own plan. The free plan covers 300 messages a month and replies are never counted.

How do I know the SMS was delivered?

Either poll GET /api/v1/messages and read each message's status, or register a webhook and receive a message.status event when the message reaches sent, delivered or failed. Delivery confirmation comes from the recipient's handset via the carrier, so timing varies by network.

Can my Java application receive SMS replies?

Yes. Poll GET /api/v1/messages?direction=inbound with the next_cursor from the previous call, or register an HTTPS webhook and receive message.received events signed with HMAC-SHA256 over the timestamp and raw body.

How fast does the message arrive?

An ordinary message is paced and usually leaves within a minute or two, subject to civil hours where the recipient is. A message marked transactional=true is handed to the phone immediately and typically reaches the handset in about a second. New lines are limited to 100 messages a day until they have warmed up.

What phone number does the recipient see?

The number of the SIM in your connected Android phone. It is your own number, so replies come straight back to you and the conversation stays in one thread.

This is a spoke of What Is an SMS API and How to Use One. Siblings: Send an SMS from Node.js, Send an SMS from Python, Send SMS From PHP, Send SMS From C#, Send SMS From Go, Send SMS From Ruby. The phone comes from Turn Your Android Phone into an SMS Gateway; the agent route is What Is an MCP Server for SMS?.

Send your first message today

Free plan, no card: 400 messages a month from your own number, with the API, webhooks and MCP included.

Get the app See pricing

Get it on Google Play

Written by , who builds SMSNET. Product facts on this page are checked against the live pricing page and the running API on the date shown above.