Recently I needed a program to move the mail from one mail box to another. I wrote the following program to accomplish this.. Hopefully someone will find it useful. I whipped this program together pretty quickly, so it's a little raw. But it'll log any error mesages to standard out.
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class MigrateMail{
public static void main(String[] args)throws Exception{
String host = "";
String username = "";
String password = "";
String migrationAddress;
Properties props = new Properties();
props.put("smtp.server.com", host);
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imap");
store.connect(host, username, password);
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
Message messages[] = folder.getMessages();
for (int i=0; i < messages.length; i++) {
try{
forward(session, messages[i], i, migrationAddress);
Thread.sleep(60000); // sleep 1 minute between emails.
}catch(Exception e){
System.out.println("Mail Failed for " + i + ", " + messages[i].getFrom()[0] + ", subject = " + messages[i].getSubject());
}
}
folder.close(false);
store.close();
}
public static void forward(Session session, Message oldMessage, int i, String migrationAddress)throws
Exception{
Message message = new MimeMessage(session);
message.setSentDate(oldMessage.getSentDate());
message.addFrom(oldMessage.getFrom());
message.addRecipient(Message.RecipientType.TO, new InternetAddress(migrationAddress));
message.setSubject(oldMessage.getSubject());
message.setContent(oldMessage.getContent(), oldMessage.getContentType());
Transport.send(message);
System.out.println("Message Send. " + i);
}
}
Here's the compile command
javac -cp "mail.jar:activation.jar:." MigrateMail.java
Here's the run command
java -cp "mail.jar:activation.jar:." MigrateMail >> mail.migration.txt
then i command z'd it w/ a bg.