import com.sun.mail.pop3.POP3Folder;
import com.sun.mail.pop3.POP3SSLStore;
import javax.mail.Session;
import javax.mail.Flags;
import javax.mail.Message;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.StringTokenizer;
import javax.mail.internet.MimeMessage;
import java.io.FileOutputStream;
import java.io.File;
import java.io.ObjectOutputStream;
import java.io.Writer;
import java.net.URL;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.Store;
import javax.mail.Folder;
import java.util.Properties;
import javax.mail.URLName;
/**
* This class is responsible for deleting e-mails.
*
* @author <a href="mailto:fzammetti@omnytex.com">Frank W. Zammetti</a>.
*/public class deletemail {
private static final String SMTP_HOST_NAME = "smtp.gmail.com";
private static final int SMTP_HOST_PORT = 465;
private static final String SMTP_AUTH_USER = "examplemail@gmail.com";
private static final String SMTP_AUTH_PWD = "examplepassword";
private Session session;
private POP3SSLStore store;
private String username;
private String password;
private POP3Folder folder;
URLName url;
public static void main(String[] args) throws Exception{
new deletemail().test();
}
public void test() throws Exception{
try{
Properties pop3props = new Properties();
//----------------------------------------------
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties pop3Props = new Properties();
pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
pop3Props.setProperty("mail.pop3.port", "995");
pop3Props.setProperty("mail.pop3.socketFactory.port", "995");
username="examplemail@gmail.com";
password="examplepassword";
url = new URLName("pop3", "pop.gmail.com", 995, "", username, password);
session = Session.getInstance(pop3Props, null);
store = new POP3SSLStore(session, url);
store.connect();
folder = (POP3Folder) store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
Message message[] = folder.getMessages();
System.out.println(message.length);
for (int i=0, n=message.length; i<n; i++) {
message[i].setFlag(Flags.Flag.DELETED, true);
System.out.println("hello world");
}
folder.close(true);
store.close();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if (folder != null) {
folder.close(true);
}
if (store != null) {
store.close();
}
} catch (Exception e) { }
}
}
}
このプログラムメッセージを実行した後、最初にinボックスに10個のメッセージmessage.length=10を含めます。長さは0に減少しますが、Gmailアカウントを開くと、メッセージはまだそこにあり、受信トレイから削除されません。