December 14, 2009

Java and POP3 with Hotmail

A simple example as we learn more on the mail protocols:

package email;

import javax.mail.*;

public class MailUtils {

public static Store getStore(Account account) throws MessagingException {
return getStore(account.Email, account.Password);
}

public static Store getStore(String email, String password) throws MessagingException {
java.util.Properties props = new java.util.Properties();
props.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.pop3.socketFactory.fallback", "false");
props.setProperty("mail.pop3.socketFactory.port", "995");

javax.mail.Session session = Session.getDefaultInstance(props);

Store store = session.getStore("pop3");
store.connect("pop3.live.com", email, password);

return store;
}

public static Folder[] getFolders(Store store) throws MessagingException
{
return store.getDefaultFolder().list("*");
}

public static Folder getFolderByUrl(Store store, String url) throws MessagingException
{
return store.getFolder(new URLName(url));
}

public static Message[] getMessages(Folder folder) throws MessagingException {
try {
folder.open(Folder.READ_ONLY);
Message[] messages = folder.getMessages();

for(Message m : messages) {
String s = m.getSubject();
System.out.print(s);
}

return messages;
}
finally {
//folder.close(false);
}
}

}

No comments:

Post a Comment