Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
javamail read mail
@Test
public String readMailTest() throws Exception {
Properties props = new Properties();
props.put("mail.imap.host", "imap.sina.cn");
Session session = Session.getDefaultInstance(props);
IMAPStore store = (IMAPStore) session.getStore("imap");
store.connect("sgmall_test_001", "sgmall_test_001");
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_WRITE);
try {
Calendar c = Calendar.getInstance();
c.add(Calendar.SECOND, -15);
SentDateTerm date = new SentDateTerm(ComparisonTerm.GT, c.getTime());// 15sec 以内的
NotTerm not = new NotTerm(new BodyTerm("退回邮件"));
BodyTerm body = new BodyTerm("验证码为(\\d+)");
FlagTerm notSeen = new FlagTerm(new Flags(Flag.SEEN), false);
// SearchTerm term = new SearchTerm();
Message[] messages = emailFolder.search(new AndTerm(new SearchTerm[] { not, body, date, notSeen }));
int countdown = 5;
while(messages.length == 0 && countdown > 0) {
messages = emailFolder.search(new AndTerm(new SearchTerm[] { not, body, date, notSeen }));
countdown--;
Thread.sleep(12000);
}
if (messages.length == 0) {
throw new RuntimeException("no matching mail found in limited timespan");
}
if (messages.length > 1) {
throw new RuntimeException("too many mails found, slow down, don't be hurry");
}
Message message = messages[messages.length - 1];
MimeMultipart part = (MimeMultipart) message.getContent();
part = (MimeMultipart) part.getBodyPart(0).getContent();
String bodyString = part.getBodyPart(0).getContent().toString();
Pattern ptn = Pattern.compile("验证码为(\\d+)");
Matcher m = ptn.matcher(bodyString);
m.find();
return m.group(1);
} finally {
emailFolder.close(true);
store.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.