Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I want to send SMS to a mobile phone from a web application, is it possible? How do I do it?
the easiest way to do this is to use an SMS gateway.
there are lots out there, the one i've used is Clickatel to which i simply post an XML request and the gateway does the rest for next to nothing.
i have done this using java and apache commons HTTP Client
Here you can find a Java SMS API project in source forge.
Apart from that, you need a Sms Gateway for the infrastructure. Some companies provide you APIs that it is becoming as easy as pie to make the program.
Step-1.
Download Mail.jar and Activation.jar (see Resources for links) and save to the Java library directory on your computer's local drive.
Step-2.
Start a new Java class in your Java Integrated Development Environment (IDE) and name it "MyMobileJava.java".
Step-3.
Enter the following Java libraries at the start of your Java class. These libraries include the required Java Mail and Communications API resources and other supporting Input/Output and Internet class libraries for sending SMS text messages.
import java.io.*;
import java.net.InetAddress;
import java.util.Properties;
import java.util.Date;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
Step-4
Place the following Java code after the library import statements in order to instantiate the Java class and assign values for the default SMS text messages.
public class SMTPSend {
public SMTPSend() {
}
public void msgsend() {
String username = "MySMSUsername";
String password = "MyPassword";
String smtphost = "MySMSHost.com";
String compression = "My SMS Compression Information";
String from = "mySMSUsername#MySMSHost.com";
String to = "PhoneNumberToText#sms.MySMSHost.com";
String body = "Hello SMS World!";
Transport myTransport = null;
Step-5
Create Java code to create a new communications session that will then be used to configure the information contained within a text message. This information will then be prepared to be sent. Enter the following Java code in your Java class at the end of the code entered in step four.
try {
Properties props = System.getProperties();
props.put("mail.smtp.auth", "true");
Session mailSession = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(compression);
msg.setText(body);
msg.setSentDate(new Date());
Step-6
Send the text message by connecting to your SMS host address, saving changes to the message, and then sending the information. To do this, enter the following Java code to finish the Java class.
myTransport = mailSession.getTransport("smtp");
myTransport.connect(smtphost, username, password);
msg.saveChanges();
myTransport.sendMessage(msg, msg.getAllRecipients());
myTransport.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] argv) {
SMTPSend smtpSend = new SMTPSend();
smtpSend.msgsend();
}
} //enter code here`
You can use this free Java sample program to send SMS from your PC using GSM modem connected to your computer to your COM port. You also need to download and install the Java comm api from Sun.
This program needs the following java files to function.
SerialConnection.java (This file is used to connect to your COM port from your java program)
SerialConnectionException.java (This file is for handling serial connection exceptions in your Java program)
SerialParameters.java (This program is used to set your COM port properties for connecting to your com port from your java program)
Sender.java (This is the program that implements runnable and sends SMS using the serial connection)
SMSClient.java (This java class is the main class that can be instantiated in your own java program and called to send SMS. This program in turn will use all the above four files internally to send out your SMS).
Download Send SMS Java sample program files
/*
*
* A free Java sample program
* A list of java programs to send SMS using your COM serial connection
* and a GSM modem
*
* #author William Alexander
* free for use as long as this comment is included
* in the program as it is
*
* More Free Java programs available for download
* at http://www.java-samples.com
*
*
* Note: to use this program you need to download all the 5 java files
* mentioned on top
*
*/
public class SMSClient implements Runnable{
public final static int SYNCHRONOUS=0;
public final static int ASYNCHRONOUS=1;
private Thread myThread=null;
private int mode=-1;
private String recipient=null;
private String message=null;
public int status=-1;
public long messageNo=-1;
public SMSClient(int mode) {
this.mode=mode;
}
public int sendMessage (String recipient, String message){
this.recipient=recipient;
this.message=message;
//System.out.println("recipient: " + recipient + " message: " + message);
myThread = new Thread(this);
myThread.start();
// run();
return status;
}
public void run(){
Sender aSender = new Sender(recipient,message);
try{
//send message
aSender.send ();
// System.out.println("sending ... ");
//in SYNCHRONOUS mode wait for return : 0 for OK,
//-2 for timeout, -1 for other errors
if (mode==SYNCHRONOUS) {
while (aSender.status == -1){
myThread.sleep (1000);
}
}
if (aSender.status == 0) messageNo=aSender.messageNo ;
}catch (Exception e){
e.printStackTrace();
}
this.status=aSender.status ;
aSender=null;
}
}
The easiest way to do this is to find an operator which supports sms's through mail..
Ex. You have Telia/Comviq/Chello or whatnot. If you send an email to; yournumber#youroperator.com it will send your email via sms to your phone.
Please have a look at SMSLib (http://smslib.org), an open source library for sending and receiving sms using a GMS modem or a mobile phone. It is really a great library.
I wrote a small maven lib for accessing the free (for customers only) web interface of the Swiss moblie operators Sunrise and Orange. You find the source on http://github.com/resmo/libjsms
Just retrieve all the cell phone Email-to-SMS (SMS Gateway) addresses and send an email to that email-to-SMS address.
Related
I need to send email from java program. I am first trying to understand basics. I found a snippet at:
https://www.javatpoint.com/example-of-sending-email-using-java-mail-api
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEmail
{
public static void main(String [] args){
String to = "sonoojaiswal1988#gmail.com";//change accordingly
String from = "sonoojaiswal1987#gmail.com";change accordingly
String host = "localhost";//or IP address
//Get the session object
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
//compose the message
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("Ping");
message.setText("Hello, this is example of sending email ");
// Send message
Transport.send(message);
System.out.println("message sent successfully....");
}catch (MessagingException mex) {mex.printStackTrace();}
}
}
My question is that as per the code, it looks like anyone can use any sender email address string and send infinite emails to any receiver email address. I am missing something in my understanding, which will prevent such scenario to happen. Please help.
I understand that this is not a programming question, but guess, it will not take too much time to answer this basic question and don't know any other equally active forum.
This example works for servers which don't need authentication. And this is usually not applicable to the smtp servers used in production. Such servers are used mostly for testing purposes where they are not exposed over the internet. Hence, although its possible to send infinite number of mails as mentioned by you, no one would be interested in doing the same.
For the servers where authentication is necessary, credentials need to be provided. And this is explained in detail in the blog mentioned by you.
I was just trying to send SMS using java as I require it in my Web App.But for testing purpose I am the code that is described in this site
And the code is as follows
package logic;
import com.harshadura.gsm.smsdura.GsmModem;
/**
* #author : Harsha Siriwardena <harshadura#gmail.com>
* #copyrights : www.Durapix.org <http://www.durapix.org>
* #license : GNU GPL v3 <http://www.gnu.org/licenses/>
*
* Example on how to simply send a SMS using the smsdura API Wrapper.
*/
public class TestSMS {
private static String port = "COM3"; //Modem Port.
private static int bitRate = 115200; //this is also optional. leave as it is.
private static String modemName = "ZTE"; //this is optional.
private static String modemPin = "0000"; //Pin code if any have assigned to the modem.
private static String SMSC = "+9477000003"; //Message Center Number ex. Mobitel
public static void main(String[] args) throws Exception {
GsmModem gsmModem = new GsmModem();
GsmModem.configModem(port, bitRate, modemName, modemPin, SMSC);
gsmModem.Sender("+94712244555", "Test Message"); // (tp, msg)
}
}
When I tried to run this,I am getting this error
-----------------------------
*** SMS-DURA - GSM MODEM SMS API WRAPPER ***
www.harshadura.com
-----------------------------
Example: Send message from a serial gsm modem.
SMSLib: A Java API library for sending and receiving SMS via a GSM modem or other supported gateways.
This software is distributed under the terms of the Apache v2.0 License.
Web Site: http://smslib.org
Version: 3.5.1
log4j:WARN No appenders could be found for logger (smslib).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Exception in thread "main" org.smslib.GatewayException: Comm library exception: java.lang.RuntimeException: javax.comm.NoSuchPortException
at org.smslib.modem.SerialModemDriver.connectPort(SerialModemDriver.java:102)
at org.smslib.modem.AModemDriver.connect(AModemDriver.java:114)
at org.smslib.modem.ModemGateway.startGateway(ModemGateway.java:189)
at org.smslib.Service$1Starter.run(Service.java:276)
Please anybody tell me how to fix this issue
basically you the program is unable to find the PORT,use
org.smslib.helper.CommPortIdentifier
to find the correct COM port from the list of ports.
I know this is not the sort of answer you expect on SO but given the alternative I think it's better than nothing.
a) Your library is reporting that your modem is not attached.
b) You don't know how to check if your modem is attached.
While not in any way related with the company I've used nexmo with great success in the past.
If it's a necessity of your app I would strongly suggest you approach the problem by the API route that will save you enormous amount of work.
There are several companies out there that provide this service and the usage is more or less straight-forward, you simply format a URL to pass parameters back to the company. Nexmo example:
// by calling a crafted url you are requesting the company to send the sms for you
urlString = "https://rest.nexmo.com/sms/json?api_key={api_key}&api_secret={api_secret}&from=MyCompany20&to=447525856424&text=helloworld";
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream()
Nexmo is NOT the only one out there providing this service. They are the only one i've had hands on experience with.
Copy the API(comm.jar),dll(win32com),properties file(javax.comm) in
1) If Net Beans tool you are using means
C:\Program Files\Java\jdk1.7.0\jre\lib\ext
and
C:\Program Files\Java\jdk1.7.0\jre\bin
2) If Eclipse tool you are using means
C:\Program Files\Java\jre7\lib\ext
and
C:\Program Files\Java\jre7\bin
as per the instructions given in Code projects.com where you downloaded this project.
Another way If you can configure your tool then do it, logic is the API's should be under your runtime JVM(jre).
and make sure that the port which is given by you should be free that is no other apps should run on it.
Yes I also got this exception to in Harshadura's SMS wrapper.Their can be two things you did not do
You did not declare any appenders in the code so at the beginning of
your code just type in this simple code to declare appenders.
package logic;
import com.harshadura.gsm.smsdura.GsmModem;
/**
* #author : Harsha Siriwardena <harshadura#gmail.com>
* #copyrights : www.Durapix.org <http://www.durapix.org>
* #license : GNU GPL v3 <http://www.gnu.org/licenses/>
*
* Example on how to simply send a SMS using the smsdura API Wrapper.
*/
public class TestSMS {
private static String port = "COM3"; //Modem Port.
private static int bitRate = 115200; //this is also optional. leave as it is.
private static String modemName = "ZTE"; //this is optional.
private static String modemPin = "0000"; //Pin code if any have assigned to the modem.
private static String SMSC = "+9477000003"; //Message Center Number ex. Mobitel
public static void main(String[] args) throws Exception {
BasicConfigurator.configure();//Declares appenders
GsmModem gsmModem = new GsmModem();
GsmModem.configModem(port, bitRate, modemName, modemPin, SMSC);
gsmModem.Sender("+94712244555", "Test Message"); // (tp, msg)
} }
Identifying the port of your GSM modem. This you can solve by going to your My Computer Icon click manage > click device manager> click modems and Identify the port of your modem.
The port you identifed then write it on your code.String port="MyPort";
I am working on an application, using java, that has the following features:
User connects his mobile to a PC using a usb cable or bluetooth.
User types a message on his PC (in the textfield provided by my software).
User types a phone number (in a textbox provided by my software).
User clicks the send button.
Then, the software should send the message to the specified phone number and appropriate charges should be applied to my mobile balance. In other words, I am directing my mobile through my software to send message to a specified number.
How shall i do that? Is core java sufficient for this purpose or i have to use j2me or is there any particular java framework that would be suitable for this?
One option is to connect the phone to the pc using serial link (COM). Need to configure the phone connected physically by USB or Bluetooth in order to appear in a COM (serial) port.
Then you need to create an application for PC (Java or whatever can open serial ports) that opens the COM port used by the phone and send the proper AT commands. Serial port can be opened by JavaComm 2.0 Win32 or more recently RxTx.
Open the serial port and write and read command by writing and reading bytes, in the same way a socket.
Then create a visual application that let user set the information like phone number for destination, text...
You need Java SE or whatever language allows you to create visual applications and opening serial ports (Java, .NET, Python...).
Some links about AT commands by serial port in Windows: 1, 2, 3.
Another option could be using native API from the mobile OS through a socket, but seems complex and using AT commands and serial port should work for all phones and the only problem is connecting the phone by serial over USB or BlueTooth and managing the serial port.
This is highly dependent on the Mobile OS you're using. Are you using Windows Mobile, Android OS, BlackBerry OS?
If you're using Android, then you should use the built in SmsManager to do that. The SmsManager can do the following:
Manages SMS operations such as sending data, text, and pdu SMS messages.
Update:
Since you're using Symbian OS, then check out the documentation for more information on sending SMS messages. I assume that you can figure out the rest (i.e. how to get the text fields for the number and the message, etc.)
Here is an example from the Symbian OS documentation:
public boolean sendSms(String number, String message){
boolean result = true;
try {
//sets address to send message
String addr = "sms://"+number;
// opens connection
MessageConnection conn = (MessageConnection) Connector.open(addr);
// prepares text message
TextMessage msg =
(TextMessage)conn.newMessage(MessageConnection.TEXT_MESSAGE);
//set text
msg.setPayloadText(message);
// send message
conn.send(msg);
conn.close();
} catch (SecurityException se) {
// probably the user has not allowed to send sms
// you may want to handle this differently
result = false;
} catch (Exception e) {
result = false;
}
return result;
}
The above snippet came from the guide on "How to Send Text SMS in Java ME"
I have Gui Application written which running on windows,and i want to connect to remote unix machine and perform actions there such like API's ,go over the log file in the machines and send back to the application the last log file or others API that i want to perform on the remote machine.
In the remote machine i don;t have application server i just have Java which installed there.
I want to use Java in order to perform remote API over the remote machine;
what is the advice ,can i use web services ,can any one please advise.
Thanks in advance.
If Java can perform the actions you're talking about, I would use Sockets to communicate with the UNIX-Machine (over TCP/IP).
Your Windows-PC would be the client sending commands to the Unix-PC.
Web services would be a bit heavy handed option, esp if you opt for the SOAP ones. If you don't have a problem with the client and server always being Java, RMI seems to be the simplest solution to this problem since it's communication between two different JVM's using the normal method calling mechanism (with some additional interfaces and rules to be followed to please the RMI specification).
The Spring Framework ships with a number of remoting options that are all very easy to setup. You can use their classes for simpler configuration of something standard like RMI or JMS, or use a lightweight web services protocol such as Spring's HTTP invoker or Hessian.
For analyzing log files of remote machines you can always use Apache Commons sftp programmatically to FTP a copy of the remote log file to your PC.
If you configure the log files to be rotatable or to rotate each time they reach a specific size, you can avoid reloading the same information over and over.
You can use Ganymed SSH-2 for Java to ssh to the remote host from Client Java App and run the commands. No need to run any additional components on remote server. You can do password based authentication or key based authentication to login to remote host. We had successfully used it to administer (start/stop/grep log files, etc.) applications running on remote UNIX hosts. You can capture output of the remote command using the StreamGobbler class provided in the package. You can pass multiple commands separated by semi-colon in one remote call.
Basic Example included in the package:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
public class Basic
{
public static void main(String[] args)
{
String hostname = "127.0.0.1";
String username = "joe";
String password = "joespass";
try
{
/* Create a connection instance */
Connection conn = new Connection(hostname);
/* Now connect */
conn.connect();
/* Authenticate.
* If you get an IOException saying something like
* "Authentication method password not supported by the server at this stage."
* then please check the FAQ.
*/
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
/* Create a session */
Session sess = conn.openSession();
sess.execCommand("uname -a && date && uptime && who");
System.out.println("Here is some information about the remote host:");
/*
* This basic example does not handle stderr, which is sometimes dangerous
* (please read the FAQ).
*/
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true)
{
String line = br.readLine();
if (line == null)
break;
System.out.println(line);
}
/* Show exit status, if available (otherwise "null") */
System.out.println("ExitCode: " + sess.getExitStatus());
/* Close this session */
sess.close();
/* Close the connection */
conn.close();
}
catch (IOException e)
{
e.printStackTrace(System.err);
System.exit(2);
}
}
}
Hi I want to write a java program where I will provide my email id and password. and I want to read all new unread messages that arrived to that email id. I donot know how to write program for that.
The below program works fine for gmail. but it does not work for yahoomail because for yahoo pop3 is not configured. I want a generic code which will work for all email id.
import java.io.*;
import java.util.*;
import javax.mail.*;
public class ReadMail {
public static void main(String args[]) throws Exception {
// String host = "pop.gmail.com";
// String user = "xyz";
// String password = "12345";
// Get system properties
Properties properties = System.getProperties();
// Get the default Session object.
Session session = Session.getDefaultInstance(properties, null);
// Get a Store object that implements the specified protocol.
Store store = session.getStore("pop3s");
//Connect to the current host using the specified username and password.
store.connect(host, user, password);
//Create a Folder object corresponding to the given name.
Folder folder = store.getFolder("inbox");
// Open the Folder.
folder.open(Folder.READ_ONLY);
Message[] message = folder.getMessages();
// Display message.
for (int i = 0; i < message.length; i++) {
System.out.println("------------ Message " + (i + 1) + " ------------");
System.out.println("SentDate : " + message[i].getSentDate());
System.out.println("From : " + message[i].getFrom()[0]);
System.out.println("Subject : " + message[i].getSubject());
System.out.print("Message : ");
InputStream stream = message[i].getInputStream();
while (stream.available() != 0) {
System.out.print((char) stream.read());
}
System.out.println();
}
folder.close(true);
store.close();
}
}
You need to know more than just login-pass. Things like mail server address, mail server type, port for connections, etc.
You should probably check out Java Mail API, or Commons Email.
UPD:
You create a Session using Session.getDefaultInstance() method (which takes connection Properties object and authenticator), get a Store from this Session using Session.getStore() method, get a Folder from that store using Store.getFolder("FOLDER_NAME") method, open that Folder, using Folder.open(Folder.READ) method, and get all messages, using something like Message[] messages = inboxFolder.getMessages();
Is that what you were looking for?
UPD2:
There is simply no way to write a generic program, which will work with any mail provider, using just server path, userID and password. Because different mail servers are configured differently. They talk differen protocols (imap/pop3/pop3 ssl) on different ports. There's always some guy, who has configured his mail server to talk imap over ssl on 31337 port only, all the other ports and protocols are banned. And this guy breaks your program. So, you'll have to specify all this properties in your properties object. Look here for properties, you'll have to specify.
UPD3:
On second thought, you actually have one option. Just try connecting to the server using different protocols. If that does not help, start iterating through ports. The one that fits is your configuration. If that's really what you want.
You need the javax.mail package, and the documentation of it. Read the documentation. Then you know.
There are two ways to do it:
1) Google provides API's to access mail you could use that library which provides more control over your mails. See here: http://code.google.com/apis/gmail/. In the same way try for other email providers.
2) Simple mail client(you could find it easily googling), but you need to look at headers to identify which mails are read/unread etc.
You need a registry where you can get the properties for a given mail service.
For instance, instead of specifying a pop3 host, you could specify the name of a .properties file that would contain the host, the port, the protocol, etc...
If your .properties file contains the protocol, for instance mail.store.protocol=pop3, you could use session.getStore() (with no argument), and the same code could be used for pop3, imap, pop3s, imaps.