Send SMS from Java

From SMS Wiki
Revision as of 17:00, 19 February 2008 by Bzurkovic (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Example code to send text messages written in Java.


Must Download

1. mail.jar from JavaMail at http://java.sun.com/products/javamail/downloads/index.html


2. activation.jar at http://java.sun.com/products/javabeans/jaf/downloads/index.html and set classpath to the location where the files are stored. This code is provided as sample only.


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.*;


public class SMTPSend {


   public SMTPSend() {
   }


   public void msgsend() {
       String username = "YourUsername";
       String password = "YourPassword";
       String smtphost = "smtp.upsidewireless.com";
       String compression = "Compression Option goes here - find out more";
       String from = "YourUsername@smtp.upsidewireless";
       String to = "DestinationPhoneNumber@sms.upsidewireless.com";
       String body = "Your Message";
       Transport tr = null;


       try {
        Properties props = System.getProperties();
        props.put("mail.smtp.auth", "true");


        // Get a Session object
        Session mailSession = Session.getDefaultInstance(props, null);


        // construct the message
        Message msg = new MimeMessage(mailSession);


        //Set message attributes
        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());


        tr = mailSession.getTransport("smtp");
        tr.connect(smtphost, username, password);
        msg.saveChanges();
        tr.sendMessage(msg, msg.getAllRecipients());
        tr.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
   }


     public static void main(String[] argv) {
         SMTPSend smtpSend = new SMTPSend();
         smtpSend.msgsend();
     }

}