Tuesday, April 1, 2014
How to Send SMS Using Java
1. Download Mail.jar and Activation.jar (see Resources for links) and save to the Java library directory on your computer's local drive.
2. Start a new Java class in your Java Integrated Development Environment (IDE) and name it 'MyMobileJava.java'.
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.*;
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;
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());
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();
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment