Monday, March 16, 2009

java : Simple java program to read mails from your gmail account

Connecting GMail using POP3 connection with SSL

POP (Post Office Protocol 3)
This protocol defines a single mailbox for a single user and a standardized way for users to access mailboxes and download messages to their computer.


To run this code u need to download Java Mail API and JavaBeans Activation Framework


/*Here is the complete tested code for ReadGmailAccount.java*/


import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.*;
import javax.activation.*;

public class ReadGmailAccount
{
public static void main(String[] args)
{
Properties props = System.getProperties();

props.put("mail.pop3.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback","false");
props.setProperty("mail.pop3.port", "995");
props.setProperty("mail.pop3.socketFactory.port", "995");

Session session = Session.getDefaultInstance(props,null);

URLName urln = new URLName("pop3","pop.gmail.com",995,null,"madan712@gmail.com","*******");//password


try
{
Store store = session.getStore(urln);

store.connect();

Folder folder = store.getFolder("INBOX");

folder.open(Folder.READ_ONLY);

Message[] message = folder.getMessages();

for (int i = 0; i < message.length; i++)
{

System.out.println("------------ Message " + (i + 1) + " ------------");

System.out.println("Subject : " + message[i].getSubject());
System.out.println("SentDate : " + message[i].getSentDate());
System.out.println("From : " + message[i].getFrom()[0]);

System.out.print("Message : ");

InputStream stream = message[i].getInputStream();
while (stream.available() != 0)
{
System.out.print((char) stream.read());
}
}

folder.close(true);
store.close();
}
catch (Exception ex)
{
System.out.println("Exception occured"+ex);
ex.printStackTrace();
}
}
}

No comments:

Post a Comment