My Mail receive programme in java i use mail.1.4.jar and activation jar in my java programme
There are 5 steps i followed to receive the email using JavaMail API.
They are:
Get the session object
create the POP3 store object and connect with the pop server
create the folder object and open it
retrieve the messages from the folder in an array and print it
close the store and folder objects
here is my code :
public class receive_Email {
public static void main(String[] args) {
String host="pop.gmail.com";
String mailStorType="pop3";
String Username="***********@gmail.com";
String Password="*******";
receiveMail(host, mailStorType, Username, Password);
}
// method for Receive email.....!
public static void receiveMail(String pop3Host,String sotreType,String user,String password){
/// 1) get session object
Properties props=new Properties();
props.put("mail.pop3.host", pop3Host );
Session sessEmail=Session.getDefaultInstance(props);
// 2) create pop3 store object and connect with pop server
try {
POP3Store emailStore=(POP3Store)sessEmail.getStore(sotreType);
emailStore.connect(user,password);
// 3) create Folder object and open it
Folder emailFolder=emailStore.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
// 4) Retrieve the messages in the folder and display it
Message[] messages=emailFolder.getMessages();
int i=0;
for(Message m : messages){
System.out.println("------------------------------------------------");
System.out.println("Email Number : "+m.getMessageNumber());
System.out.println("Subject : "+m.getSubject());
System.out.println("From : "+m.getFrom());
try {
System.out.println("Subject : "+m.getContent().toString());
} catch (IOException e) {
System.out.println("No messages are available.............!");
e.printStackTrace();
}
} // end for loop
// 5) Close the Folder and email store
emailFolder.close(false);
emailStore.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
Exception I got is :
javax.mail.MessagingException: Connect failed;
nested exception is:
java.net.ConnectException: Connection timed out: connect
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:148)
at javax.mail.Service.connect(Service.java:275)
at javax.mail.Service.connect(Service.java:156)
at javax.mail.Service.connect(Service.java:176)
at com.mwh.DBConnect.receive_Email.receiveMail(receive_Email.java:37)
at com.mwh.DBConnect.receive_Email.main(receive_Email.java:22)
Caused by: java.net.ConnectException: Connection timed out: connect
.....
..
any suggestions to get rid of this exception... thanks in advance....