Kontera

Thursday, January 23, 2014

Java Code to Copy eMail from One Folder to Another in Gmail

The following java code copies the eMails from one folder to another folder in gmail.

Steps

  1. First create a new label in gmail by clicking the manage label link
  2. Create new label(Name of the source folder)
  3. Give the name of new label in source folder(eg:PHISH) place in the code
  4. Run the code  











Libraries Required :- JavaMail Download  

Source Code
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;

/**
 *
 * @Sarju
 */
public class MoveMailToFolder {
    public static void main(String[] args) {
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "imaps");
        try {
            Session session = Session.getInstance(props, null);
            Store store = session.getStore();
            //eMail Authentication
            store.connect("imap.gmail.com", "username@gmail.com", "password");
            Folder inbox = store.getFolder("INBOX");//Source folder
            inbox.open(Folder.READ_WRITE);
            System.out.println("Opened source...");
            Folder spam = store.getFolder("PHISH"); // Destination folder
            spam.open(Folder.READ_WRITE);
            //Get the latest message
            Message[] msgs = inbox.getMessages(inbox.getMessageCount()-inbox.getUnreadMessageCount(),inbox.getMessageCount());
            inbox.copyMessages(msgs, spam);
            System.out.println("Copied messages...");
            inbox.close(false);
            store.close();
            } catch (Exception mex) {
        }
    }
}

0 comments:

Post a Comment