Day to Day Java Java and related Topics

10Mar/100

Need to get data from your pop/imap accounts?

Yesterday I needed to get some data from a number of email accounts, and of course googled it a bit before I started. Our current system had support for this, hence using Java Sockets and commands to the email server. This proved to be slow and not accurate.

Java ships with a built in API for this, the javax.mail. The goal was to instantiate a connection and get the total quota and used quota for an account.

I needed to use the Imap part of javax.mail to get quota for the account.

Here is how I did it:

public Long getQuota(String username, String password, String server) {
	// Instantiate a new mail session
	Session mailSession = Session.getInstance(new Properties());
 
	try {
	    // Connect to the imap server using server host, username(account) and password
	    IMAPStore imapStore = (IMAPStore)mailSession.getStore("imap");
	    imapStore.connect(server, username, password);
 
	    IMAPFolder folder = (IMAPFolder) imapStore.getFolder("INBOX");
	    folder.open(Folder.READ_ONLY);
 
	    Long totalQuotaForAccount = 0l;
 
	    // Make sure the account is activated and contains messages
	    if (folder.exists() && folder.getMessageCount() > 0) {
		Quota[] quotas = folder.getQuota();
 
		for (Quota quota : quotas) {
		    for (Quota.Resource resource : quota.resources) {
		        totalQuotaForAccount += resource.usage;
		    }
		}
	    }
 
	    imapStore.close();
	    return totalQuotaForAccount;
	} catch (MessagingException e) {
	    logger.error("Failed to connect or get quota for mail user " + username, e);
	    return 0l;
	}
}

As you can see I used the IMAPStore. IMAPStore gives the quota of the account, but you can of course also use POP3Store. This API supports getting messages, folders, sending messages and more. http://java.sun.com/products/javamail/javadocs/javax/mail/package-summary.html

No related posts.

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)

No trackbacks yet.