JAVA示例搜索IMAP邮箱里的邮件
JAVA示例:搜索IMAP邮箱里的邮件
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import javax.mail.search.FromStringTerm;
public class SearchMail {
public static void main(String[] args) throws Exception {
//config
String protocol = “imap”;
String host = “mailsv01.xxxxxxxx”;
int port = 993;
String user = “xx”;
String password = “xx”;
String mbox = “INBOX”;
Properties props = System.getProperties();
Session sess = Session.getInstance(props, null);
// sess.setDebug(true);
Store st = sess.getStore(“imaps”);
st.connect(host, port, user, password);
Folder fol = st.getFolder(mbox);
SearchMail one=new SearchMail();
if (fol.exists()) {
for (Folder f : fol.list()) {
System.out.printf(“box:%s”, f.getName());
}
fol.open(Folder.READ_ONLY);
for (Message m : one.search(fol)) {
System.out.printf("/n来自%s /n标题%s/n大小%d/n",
Add2Str(m.getFrom()), m.getSubject(), m.getSize());
}
fol.close(false);
} else {
System.out.printf("%s is not exist.", mbox);
}
st.close();
}
// Message[] list(Folder f) {
// try {
// return f.getMessages();
// } catch (MessagingException e) {
// e.printStackTrace();
// return null;
// }
// }
Message[] search(Folder f) {
try {
return f.search(new FromStringTerm(“xxxxxxxx”));
} catch (MessagingException e) {
e.printStackTrace();
return null;
}
}
public static String Add2Str(Address[] a) {
if (a == null) {
return null;
}
StringBuilder sb = new StringBuilder("");
for (Address adr : a) {
InternetAddress ia = (InternetAddress) adr;
sb.append(ia.getAddress());
}
return sb.toString();
}
}