How to send sms in java?
Cohen
-
iso03 -
iso03 -
Hello everyone!
So, I wanted to program a small Java program that would send SMS. But I have a lot of questions:
1) Is it possible to send SMS for free in Java?
2) How do we use the "class" if there is one... (I couldn't find it in the API)
3) Is there anything else to know before getting started?
Thanks in advance!
So, I wanted to program a small Java program that would send SMS. But I have a lot of questions:
1) Is it possible to send SMS for free in Java?
2) How do we use the "class" if there is one... (I couldn't find it in the API)
3) Is there anything else to know before getting started?
Thanks in advance!
12 réponses
Bonjour tout le monde, contrairement à certains, moi, je suis sur un projet où je dois réaliser un programme Java pour envoyer des SMS via le modem CDMA. Mais je n'arrive pas à trouver certains packages qui me permettront de faire fonctionner mon programme. Je vous envoie les messages d'erreur qui s'affichent après la compilation :
-package javax.comm does not exist
-package org.apache.log4j does not exist
-cannot find symbol class logger
Voici le code
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.StringTokenizer;
import java.util.TooManyListenersException;
import javax.comm.CommDriver;
import javax.comm.CommPortIdentifier;
import javax.comm.CommPortOwnershipListener;
import javax.comm.NoSuchPortException;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.SerialPortEvent;
import javax.comm.SerialPortEventListener;
import javax.comm.UnsupportedCommOperationException;
import org.apache.log4j.Logger;
/class Sms implements SerialPortEventListener, CommPortOwnershipListener
{
/*
* Instance Object Logger
*/
private static Logger logger = Logger.getLogger(Sms.class);
/*
* Constance status
*/
public static final int SC_OK = 0;
public static final int SC_ERROR = 1;
public static final int SC_PDU_PARSE_ERROR = 2;
/*
* Flux I/O
*/
private OutputStream outStream;
private InputStream inStream;
/*
* Read incoming SMS from SIM
*/
public IncomingSms rx_sms = null;
/*
* Config Serial Port
*/
private SerialParameters parameters;
/*
* Communication scan port
*/
private CommPortIdentifier portId;
/*
* Communication in serial port
*/
private SerialPort sPort;
/*
* Status comm port
*/
public int portStatus = OK;
private static Boolean portStatusLock = new Boolean(true);
private boolean POLLING_FLAG;
private String portStatusMsg = "";
/*
* Type of response
*/
private static final int OK = 1;
private static final int WAIT = 2;
private static final int ERROR = 3;
private static final int WMSG = 4;
private static final int RMSG = 5;
private static final int ECHO = 6;
private static final int TIMEOUT = 7;
/*
* Buffer serial incoming event
*/
private byte[] readBuffer = new byte[20000];
private int bufferOffset = 0; // serialEvent
/*
* LF CR
*/
private static final String lfcr = "\r\n";
/*
* Default index memory is 1
*/
private int indexCurrentMemory = 1;
/*
* Default memory is "SM"
*/
private String currentMemory = "\"SM\"";
/**
* Constructor!
*
* @param parameters
*/
public Sms(SerialParameters parameters)
{
this.parameters = parameters;
}
/**
* Initialize driver to be able to connect to serial port
* in case application is running from Windows
* as you might expect no driver initialization is required on linux
* ensure you initialize only once on Windows so as to avoid multiple port enumeration
*
* @return String "successful" or "failure"
*/
public String initializeWinDrivers()
{
String drivername = "com.sun.comm.Win32Driver";
try
{
CommDriver driver = (CommDriver) Class.forName(drivername).newInstance();
driver.initialize();
return "successful";
}
catch (Throwable th)
{
// Discard it
return "failure";
}
}
/**
* Return type of serial port (depend type of driver!) Driver=com.sun.comm.Win32Driver (window)
* Driver=gnu.io.RXTXCommDriver (all platform)
*
* @param portType
* @return String with driver type
*/
static String getPortTypeName(int portType)
{
// we use on window...
switch (portType)
{
case CommPortIdentifier.PORT_PARALLEL :
return "Parallel";
case CommPortIdentifier.PORT_SERIAL :
return "Serial";
default :
return "unknown type";
}
}
/**
* Open serial connection with COM port
*
* @param _port
* @throws IOException
*/
public void openConnection(String _port) throws IOException
{
openConnection(_port, null);
}
/**
* Open serial connection with COM port
*
* @param _port
* @param _pinNumber
* @throws IOException
*/
public void openConnection(String _port, String _pinNumber) throws IOException
{
String port = _port;
if (_port == null) port = parameters.getPortName();
// Obtain a CommPortIdentifier object for the port you want to open.
try
{
portId = CommPortIdentifier.getPortIdentifier(port);
}
catch (NoSuchPortException e)
{
e.printStackTrace();
throw new IOException(e.getMessage());
}
// Open the port represented by the CommPortIdentifier object. Give
// the open call a relatively long timeout of 30 seconds to allow
// a different application to relinquish the port if the user
// wants to.
try
{
sPort = (SerialPort) portId.open("MobileAccess", 5000);
}
catch (PortInUseException e)
{
throw new IOException(e.getMessage());
}
// Set the parameters of the connection. If they won't set, close the
// port before throwing an exception.
try
{
setConnectionParameters();
}
catch (IOException e)
{
sPort.close();
throw e;
}
// Open the input and output streams for the connection. If they won't
// open, close the port before throwing an exception.
try
{
outStream = sPort.getOutputStream();
inStream = sPort.getInputStream();
}
catch (IOException e)
{
sPort.close();
throw new IOException("Error opening i/o streams");
}
// Add this object as an event listener for the serial port.
try
{
sPort.addEventListener(this);
}
catch (TooManyListenersException e)
{
sPort.close();
throw new IOException("too many listeners added");
}
// Set notifyOnDataAvailable to true to allow event driven input.
sPort.notifyOnDataAvailable(true);
// Add ownership listener to allow ownership event handling.
portId.addPortOwnershipListener(this);
// init modem connection with pin number
initializeModem(_pinNumber);
}
/**
* Initialize modem with PIN number
*
* @param pinNumber
*/
private void initializeModem(String pinNumber)
{
atCmd("ATE0", 0, 1000); // turn off command echo
atCmd("AT+CMEE=2", 0, 500); // verbose all messages
atCmd("AT+CMGF=0", 0, 500); // set Pdu mode (default binary)
//atCmd("AT+CNMI=0,0,0,0", 0, 500);// disable indications -direct to TE?
if (pinNumber != null)
{
//enter pin number
atCmd("AT+CPIN=\"" + pinNumber + "\"", 0, 1000);
if (portStatus == ERROR)
{
logger.error("The pin number " + pinNumber + " is INCORRECT. Please try again.");
// close session!
this.close();
}
}
}
/**
* List open serial port
*
* @return Array String
*/
public String[] listPorts()
{
Enumeration ports = CommPortIdentifier.getPortIdentifiers();
ArrayList portList = new ArrayList();
String portArray[] = null;
while (ports.hasMoreElements())
{
CommPortIdentifier port = (CommPortIdentifier) ports.nextElement();
if (port.getPortType() == CommPortIdentifier.PORT_SERIAL)
{
portList.add(port.getName());
}
portArray = (String[]) portList.toArray(new String[0]);
}
return portArray;
}
/**
* Handles ownership events. If a PORT_OWNERSHIP_REQUESTED event is received a dialog box is created asking the user
* if they are willing to give up the port. No action is taken on other types of ownership events.
*/
public void ownershipChange(int type)
{
if (type == CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED)
{
logger.debug("PORT_OWNERSHIP_REQUESTED received : Your port has been requested by another application...");
this.close();
}
else if (type == CommPortOwnershipListener.PORT_OWNED)
{
logger.debug("PORT_OWNED received!");
}
else if (type == CommPortOwnershipListener.PORT_UNOWNED)
{
logger.debug("PORT_UNOWNED received!");
}
}
/**
* Sets the connection parameters to the setting in the parameters object. If set fails return the parameters object
* to original settings and throw exception.
*/
private void setConnectionParameters() throws IOException
{
// Save state of parameters before trying a set.
int oldBaudRate = sPort.getBaudRate();
int oldDatabits = sPort.getDataBits();
int oldStopbits = sPort.getStopBits();
int oldParity = sPort.getParity();
int oldFlowControl = sPort.getFlowControlMode();
// Set connection parameters, if set fails return parameters object
// to original state.
try
{
sPort.setSerialPortParams(parameters.getBaudRate(), parameters.getDatabits(), parameters.getStopbits(),
parameters.getParity());
}
catch (UnsupportedCommOperationException e)
{
parameters.setBaudRate(oldBaudRate);
parameters.setDatabits(oldDatabits);
parameters.setStopbits(oldStopbits);
parameters.setParity(oldParity);
parameters.setFlowControlIn(oldFlowControl);
parameters.setFlowControlOut(oldFlowControl);
throw new IOException("Unsupported parameter");
}
// Set flow control.
try
{
sPort.setFlowControlMode(parameters.getFlowControlIn() | parameters.getFlowControlOut());
sPort.enableReceiveThreshold(1);
sPort.enableReceiveTimeout(2000); // timeout 2s ?!
}
catch (UnsupportedCommOperationException e)
{
throw new IOException("Unsupported flow control");
}
}
// To be used to send AT command via the IR/serial link to the mobile
// device (for standard AT commands use mode=0)
private synchronized int atCmd(String cmd, int mode, int timeout)
{
-package javax.comm does not exist
-package org.apache.log4j does not exist
-cannot find symbol class logger
Voici le code
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.StringTokenizer;
import java.util.TooManyListenersException;
import javax.comm.CommDriver;
import javax.comm.CommPortIdentifier;
import javax.comm.CommPortOwnershipListener;
import javax.comm.NoSuchPortException;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.SerialPortEvent;
import javax.comm.SerialPortEventListener;
import javax.comm.UnsupportedCommOperationException;
import org.apache.log4j.Logger;
/class Sms implements SerialPortEventListener, CommPortOwnershipListener
{
/*
* Instance Object Logger
*/
private static Logger logger = Logger.getLogger(Sms.class);
/*
* Constance status
*/
public static final int SC_OK = 0;
public static final int SC_ERROR = 1;
public static final int SC_PDU_PARSE_ERROR = 2;
/*
* Flux I/O
*/
private OutputStream outStream;
private InputStream inStream;
/*
* Read incoming SMS from SIM
*/
public IncomingSms rx_sms = null;
/*
* Config Serial Port
*/
private SerialParameters parameters;
/*
* Communication scan port
*/
private CommPortIdentifier portId;
/*
* Communication in serial port
*/
private SerialPort sPort;
/*
* Status comm port
*/
public int portStatus = OK;
private static Boolean portStatusLock = new Boolean(true);
private boolean POLLING_FLAG;
private String portStatusMsg = "";
/*
* Type of response
*/
private static final int OK = 1;
private static final int WAIT = 2;
private static final int ERROR = 3;
private static final int WMSG = 4;
private static final int RMSG = 5;
private static final int ECHO = 6;
private static final int TIMEOUT = 7;
/*
* Buffer serial incoming event
*/
private byte[] readBuffer = new byte[20000];
private int bufferOffset = 0; // serialEvent
/*
* LF CR
*/
private static final String lfcr = "\r\n";
/*
* Default index memory is 1
*/
private int indexCurrentMemory = 1;
/*
* Default memory is "SM"
*/
private String currentMemory = "\"SM\"";
/**
* Constructor!
*
* @param parameters
*/
public Sms(SerialParameters parameters)
{
this.parameters = parameters;
}
/**
* Initialize driver to be able to connect to serial port
* in case application is running from Windows
* as you might expect no driver initialization is required on linux
* ensure you initialize only once on Windows so as to avoid multiple port enumeration
*
* @return String "successful" or "failure"
*/
public String initializeWinDrivers()
{
String drivername = "com.sun.comm.Win32Driver";
try
{
CommDriver driver = (CommDriver) Class.forName(drivername).newInstance();
driver.initialize();
return "successful";
}
catch (Throwable th)
{
// Discard it
return "failure";
}
}
/**
* Return type of serial port (depend type of driver!) Driver=com.sun.comm.Win32Driver (window)
* Driver=gnu.io.RXTXCommDriver (all platform)
*
* @param portType
* @return String with driver type
*/
static String getPortTypeName(int portType)
{
// we use on window...
switch (portType)
{
case CommPortIdentifier.PORT_PARALLEL :
return "Parallel";
case CommPortIdentifier.PORT_SERIAL :
return "Serial";
default :
return "unknown type";
}
}
/**
* Open serial connection with COM port
*
* @param _port
* @throws IOException
*/
public void openConnection(String _port) throws IOException
{
openConnection(_port, null);
}
/**
* Open serial connection with COM port
*
* @param _port
* @param _pinNumber
* @throws IOException
*/
public void openConnection(String _port, String _pinNumber) throws IOException
{
String port = _port;
if (_port == null) port = parameters.getPortName();
// Obtain a CommPortIdentifier object for the port you want to open.
try
{
portId = CommPortIdentifier.getPortIdentifier(port);
}
catch (NoSuchPortException e)
{
e.printStackTrace();
throw new IOException(e.getMessage());
}
// Open the port represented by the CommPortIdentifier object. Give
// the open call a relatively long timeout of 30 seconds to allow
// a different application to relinquish the port if the user
// wants to.
try
{
sPort = (SerialPort) portId.open("MobileAccess", 5000);
}
catch (PortInUseException e)
{
throw new IOException(e.getMessage());
}
// Set the parameters of the connection. If they won't set, close the
// port before throwing an exception.
try
{
setConnectionParameters();
}
catch (IOException e)
{
sPort.close();
throw e;
}
// Open the input and output streams for the connection. If they won't
// open, close the port before throwing an exception.
try
{
outStream = sPort.getOutputStream();
inStream = sPort.getInputStream();
}
catch (IOException e)
{
sPort.close();
throw new IOException("Error opening i/o streams");
}
// Add this object as an event listener for the serial port.
try
{
sPort.addEventListener(this);
}
catch (TooManyListenersException e)
{
sPort.close();
throw new IOException("too many listeners added");
}
// Set notifyOnDataAvailable to true to allow event driven input.
sPort.notifyOnDataAvailable(true);
// Add ownership listener to allow ownership event handling.
portId.addPortOwnershipListener(this);
// init modem connection with pin number
initializeModem(_pinNumber);
}
/**
* Initialize modem with PIN number
*
* @param pinNumber
*/
private void initializeModem(String pinNumber)
{
atCmd("ATE0", 0, 1000); // turn off command echo
atCmd("AT+CMEE=2", 0, 500); // verbose all messages
atCmd("AT+CMGF=0", 0, 500); // set Pdu mode (default binary)
//atCmd("AT+CNMI=0,0,0,0", 0, 500);// disable indications -direct to TE?
if (pinNumber != null)
{
//enter pin number
atCmd("AT+CPIN=\"" + pinNumber + "\"", 0, 1000);
if (portStatus == ERROR)
{
logger.error("The pin number " + pinNumber + " is INCORRECT. Please try again.");
// close session!
this.close();
}
}
}
/**
* List open serial port
*
* @return Array String
*/
public String[] listPorts()
{
Enumeration ports = CommPortIdentifier.getPortIdentifiers();
ArrayList portList = new ArrayList();
String portArray[] = null;
while (ports.hasMoreElements())
{
CommPortIdentifier port = (CommPortIdentifier) ports.nextElement();
if (port.getPortType() == CommPortIdentifier.PORT_SERIAL)
{
portList.add(port.getName());
}
portArray = (String[]) portList.toArray(new String[0]);
}
return portArray;
}
/**
* Handles ownership events. If a PORT_OWNERSHIP_REQUESTED event is received a dialog box is created asking the user
* if they are willing to give up the port. No action is taken on other types of ownership events.
*/
public void ownershipChange(int type)
{
if (type == CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED)
{
logger.debug("PORT_OWNERSHIP_REQUESTED received : Your port has been requested by another application...");
this.close();
}
else if (type == CommPortOwnershipListener.PORT_OWNED)
{
logger.debug("PORT_OWNED received!");
}
else if (type == CommPortOwnershipListener.PORT_UNOWNED)
{
logger.debug("PORT_UNOWNED received!");
}
}
/**
* Sets the connection parameters to the setting in the parameters object. If set fails return the parameters object
* to original settings and throw exception.
*/
private void setConnectionParameters() throws IOException
{
// Save state of parameters before trying a set.
int oldBaudRate = sPort.getBaudRate();
int oldDatabits = sPort.getDataBits();
int oldStopbits = sPort.getStopBits();
int oldParity = sPort.getParity();
int oldFlowControl = sPort.getFlowControlMode();
// Set connection parameters, if set fails return parameters object
// to original state.
try
{
sPort.setSerialPortParams(parameters.getBaudRate(), parameters.getDatabits(), parameters.getStopbits(),
parameters.getParity());
}
catch (UnsupportedCommOperationException e)
{
parameters.setBaudRate(oldBaudRate);
parameters.setDatabits(oldDatabits);
parameters.setStopbits(oldStopbits);
parameters.setParity(oldParity);
parameters.setFlowControlIn(oldFlowControl);
parameters.setFlowControlOut(oldFlowControl);
throw new IOException("Unsupported parameter");
}
// Set flow control.
try
{
sPort.setFlowControlMode(parameters.getFlowControlIn() | parameters.getFlowControlOut());
sPort.enableReceiveThreshold(1);
sPort.enableReceiveTimeout(2000); // timeout 2s ?!
}
catch (UnsupportedCommOperationException e)
{
throw new IOException("Unsupported flow control");
}
}
// To be used to send AT command via the IR/serial link to the mobile
// device (for standard AT commands use mode=0)
private synchronized int atCmd(String cmd, int mode, int timeout)
{
Here
to send an SMS, you need to create a program that sends SMS via a mobile phone modem, for that you need to know how to communicate over a serial port, "the commAPI from Sun for example, which is a good base if the program is in Java" and also be well-versed in AT commands.
to send the SMS, you will always need a phone with a subscription, and the SMS will be counted against your plan "the price of an SMS"
to send an SMS, you need to create a program that sends SMS via a mobile phone modem, for that you need to know how to communicate over a serial port, "the commAPI from Sun for example, which is a good base if the program is in Java" and also be well-versed in AT commands.
to send the SMS, you will always need a phone with a subscription, and the SMS will be counted against your plan "the price of an SMS"
Second solution: use a website that offers free SMS sending.
However, you will need to verify that they do not track robots.
--
Please Insert COIN!
However, you will need to verify that they do not track robots.
--
Please Insert COIN!
Good evening everyone,
apparently this site offers what everyone is desperately looking for
http://mmsgratuit.c.la
apparently this site offers what everyone is desperately looking for
http://mmsgratuit.c.la
Hello,
as part of my first internship, I used an existing API on SourceForge called jSMSEngine. It contains the classes needed to receive and send SMS via a directory. I tried it, and it works fine even though configuring the right port can sometimes be a bit tricky.
as part of my first internship, I used an existing API on SourceForge called jSMSEngine. It contains the classes needed to receive and send SMS via a directory. I tried it, and it works fine even though configuring the right port can sometimes be a bit tricky.
In this case, you need to specify the path of these packages in the classpath.... I didn’t know that the comm package existed, I would have thought it was a syntax error... everyone can make mistakes xD
To specify the path in the classpath, either configure the environment variable $CLASSPATH, or when compiling, indicate it with --classpath:path_to_the_package
To specify the path in the classpath, either configure the environment variable $CLASSPATH, or when compiling, indicate it with --classpath:path_to_the_package
Hello everyone, my name is Imene from Algeria "Relizane." I would like to know how to vote, and I send my best regards to Amel B and all the candidates.