Sunday, April 15, 2012

how ro get unread mails from gmail using java

/*
 *  This is the code for read the unread mails from your mail account.
 *  Requirements:
 *      JDK 1.5 and above
 *      Jar:mail.jar
 *
 */
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.Flags.Flag;
import javax.mail.search.FlagTerm;

public class MailReader {
    Folder inbox;

    // Constructor of the calss.
    public MailReader() {
        /*   Set the mail properties  */
        Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", "imaps");
        try {
            /*   Create the session and get the store for read the mail. */
            Session session = Session.getDefaultInstance(props, null);
            Store store = session.getStore("imaps");
            store.connect("imap.gmail.com", "xxxxxxxxx@gmail.com ", "xxxxxxxxx");

            /*   Mention the folder name which you want to read. */
            inbox = store.getFolder("Inbox");
            System.out.println("No of Unread Messages : "
                    + inbox.getUnreadMessageCount());

            /* Open the inbox using store. */
            inbox.open(Folder.READ_ONLY);

            /*   Get the messages which is unread in the Inbox */
            Message messages[] = inbox.search(new FlagTerm(
                    new Flags(Flag.SEEN), false));

            /* Use a suitable FetchProfile    */
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            fp.add(FetchProfile.Item.CONTENT_INFO);
            inbox.fetch(messages, fp);

            try {
                printAllMessages(messages);
                inbox.close(true);
                store.close();
            } catch (Exception ex) {
                System.out.println("Exception arise at the time of read mail");
                ex.printStackTrace();
            }
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
            System.exit(1);
        } catch (MessagingException e) {
            e.printStackTrace();
            System.exit(2);
        }
    }

    public void printAllMessages(Message[] msgs) throws Exception {
        for (int i = 0; i < msgs.length; i++) {
            System.out.println("MESSAGE #" + (i + 1) + ":");
            printEnvelope(msgs[i]);
        }
    }

    /* &nbsp; Print the envelope(FromAddress,ReceivedDate,Subject)&nbsp; */
    public void printEnvelope(Message message) throws Exception {
        Address[] a;
        // FROM
        if ((a = message.getFrom()) != null) {
            for (int j = 0; j < a.length; j++) {
                System.out.println("FROM: " + a[j].toString());
            }
        }
        // TO
        if ((a = message.getRecipients(Message.RecipientType.TO)) != null) {
            for (int j = 0; j < a.length; j++) {
                System.out.println("TO: " + a[j].toString());
            }
        }
        String subject = message.getSubject();
        Date receivedDate = message.getReceivedDate();
        String content = message.getContent().toString();
        System.out.println("Subject : " + subject);
        System.out.println("Received Date : " + receivedDate.toString());
        //System.out.println("Content : " + content);
        getContent(message);
    }

    public void getContent(Message msg) {
        try {
            String contentType = msg.getContentType();
            //System.out.println("Content Type : " + contentType);
            Multipart mp = (Multipart) msg.getContent();
            int count = mp.getCount();
            System.out.println("count--->"+count);
            for (int i = 0; i < count-1; i++) {
                dumpPart(mp.getBodyPart(i));
            }
        } catch (Exception ex) {
            System.out.println("Exception arise at get Content");
            ex.printStackTrace();
        }
    }

    public void dumpPart(Part p) throws Exception {
        // Dump input stream ..
        InputStream is = p.getInputStream();
        // If "is" is not already buffered, wrap a BufferedInputStream
        // around it.
        if (!(is instanceof BufferedInputStream)) {
            is = new BufferedInputStream(is);
        }
        int c;
        System.out.println("Message : ");
        while ((c = is.read()) != -1) {
            System.out.write(c);
        }
    }

}




Write this code in ur servlet:

MailReader mr=new MailReader();


how to send SMS using javamail

String username = "my mobile number"
String password = "my way2sms password"
String smtphost = "site3.way2sms.com";  
 String from = "my mobile number@site3.way2sms.com";
 String to = "receiver mobile number@site3.way2sms.com";
 String body = "Hello SMS World!"
Transport myTransport = null; 
         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.setText(body); msg.setSentDate(new Date());   
myTransport = mailSession.getTransport("smtp"); 
myTransport.connect(smtphost, username, password);
 msg.saveChanges();
 myTransport.sendMessage(msg, msg.getAllRecipients()); 
myTransport.close(); 
out.print("sent"); 
} catch (Exception e) { e.printStackTrace(); }



Monday, April 9, 2012

Thursday, April 5, 2012

JSP Elements


A JSP page can have two types of data:
  • Template Data: It is the static part of a jsp page. Anything that is copied as it is directly to the response by the JSP server is known as template data.
  • JSP Elements: It is the dynamic part of a jsp page. Anything that is translated and executed by the JSP server is known as JSP element.
There are three types of JSP elements:
Directive Elements: The directive elements, contains the information about the page itself that remains the same between requests for the page. The general directive syntax is:
<%@ directiveName attr1="value1" attr2="value2" %>
The directive name and all attribute names are case-sensitive and the attribute values can be enclosed with single quotes instead of double quotes.
Action Element: Action elements generally performs some action depending on the information required at when the JSP page is requested by a browser. An action can access parameters sent with the request in order to lookup the database.
The general syntax for the action elements is:
<action_name attribute=value ...>action_body</action_name>
<action_name attribute=value .../>
Scripting Element: A JSP element is an element that provides embedded Java statements. A JSP page can have three types of scripting elements:
  • Declaration Element: A JSP element provides the capability of inserting Java declaration statements into the Servlet class. Here is the syntax for the declaration element.
   <%! Java decalaration statements %>
  • Scriptlet Element: A JSP element provides the capability of embedding Java expressions to be evaluated as part of the service method of the Servlet class. An scripting element can be written in two ways:
  <% Java statements %>
  • Expression Element: A JSP element provides the capability of embedding Java expressions to be evaluated as part of the service method of the Servlet class. An expression element can be written in two ways: <% Java expressoins %>