首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 使用 SMSLib 透過短信貓發送簡訊

     編輯:Java 相關知識

Java 整合 SMSLib 透過串口發送 SMS 完整指南

SMSLib 是成熟的 Java 簡訊庫,支援透過 GSM Modem(短信貓)、SMPP、HTTP 等閘道發送/接收簡訊。本文以串口模式為例,說明環境配置、核心程式碼與常見坑點。

環境準備 (Windows + JDK 8+)

  1. 下載 smslib-v3.3.0.jar(或較新版)、comm.jar (JavaComm)、log4j-1.2.x.jar。
  2. 將 javax.comm.properties 放入 `/jre/lib/`。
  3. 將 win32com.dll 放入 `/jre/bin/`。
  4. 將 comm.jar 放入 `/jre/lib/ext/` 或專案 classpath。
  5. 確認短信貓已正確安裝驅動,記下 COM 埠號(如 COM3)與波特率(通常 9600/115200)。

發送簡訊核心類

import org.smslib.*;
import org.smslib.modem.SerialModemGateway;

public class SmsSender {

    public void sendSms(String phoneNumbers, String content) {
        Service service = Service.getInstance();

        // 設定串口閘道
        SerialModemGateway gateway = new SerialModemGateway(
            "modem.com3", "COM3", 9600, "Wavecom", ""); // 製造商/型號可留空
        gateway.setInbound(true);   // 接收
        gateway.setOutbound(true);  // 發送
        gateway.setSimPin("0000");  // SIM PIN,無則空字串
        gateway.setOutboundNotification(new OutboundNotification() {
            @Override public void process(String gatewayId, OutboundMessage msg) {
                System.out.println("已發送:" + msg.getRecipient() + " - " + msg.getText());
            }
        });

        service.addGateway(gateway);

        try {
            service.startService();
            System.out.println("服務啟動成功");

            String[] phones = phoneNumbers.split(",");
            for (String phone : phones) {
                OutboundMessage msg = new OutboundMessage(phone.trim(), content);
                msg.setEncoding(Message.MessageEncodings.ENCUCS2); // 中文需 UCS2
                service.sendMessage(msg);
                System.out.println("發送給 " + phone + " 成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            service.stopService();
        }
    }

    public static void main(String[] args) {
        new SmsSender().sendSms("0912345678,0923456789", "測試簡訊內容");
    }
}

常見問題排查

現象可能原因解決
UnsatisfiedLinkError: no rxtxSerial缺少 win32com.dll / librxtxSerial.so確認 DLL/so 放在正確路徑 (jre/bin 或 -Djava.library.path)
CommPortIdentifier: no ports foundjavax.comm.properties 內容錯誤檔案內容應為:Driver=com.sun.comm.Win32Driver
發送失敗 CMS ERROR: 304SIM 卡未就緒/欠費/訊號差用終端機 (PuTTY) 發 AT 指令測試:AT+CPIN? / AT+CSQ
中文亂碼編碼未設為 UCS2msg.setEncoding(MessageEncodings.ENCUCS2)

現代替代方案

  • HTTP API 閘道:多家電信商提供 REST API(如 Twilio、Vonage、國內雲通訊廠商),無需硬體、支援高併發、有送達報告。
  • SMPP 協定:大量發送專用,需向電信商申請 SMPP 帳號,使用 JSMPP 庫。
  • Android 手機做閘道:小規模測試可用 Android SMS Library 搭配廢棄手機。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved