我正在尝试懒惰下载电子邮件。基本上问题是我的电子邮件很重。所以我只下载主题和消息ID,只有在需要的时候我才会下载其余的电子邮件。
第一步是下载主题和消息ID:
public void downloadInBackground(EmailAccount emailAccount, String folderName) {
List<Email> emails = new ArrayList<Email>();
Message[] message = null;
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props, null);
Store store = null;
Folder folder = null;
try {
Log.getInstance().d("xxx", "starting dowanloading");
store = session.getStore("imaps");
store.connect(emailAccount.getImapServer(), emailAccount.getUsername(),
emailAccount.getPassword());
folder = store.getFolder(folderName);
folder.open(Folder.READ_ONLY);
message = folder.getMessages();
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add("Subject"); fp.add("From"); fp.add("To"); fp.add("Cc"); fp.add("Bcc"); fp.add("ReplyTo"); fp.add("Date");
folder.fetch(message, fp);
for (int i = 0; i < message.length; i++) {
Message m = message[i];
String emailId = null;
m.getHeader("Message-Id");
Enumeration<Header> headers = m.getAllHeaders();
while (headers.hasMoreElements()) {
Header h = headers.nextElement();
String mID = h.getName();
if (StringUtils.containsIgnoreCase(mID, "Message-ID")) {
emailId = h.getValue();
}
}
if (emailId != null) {
Email newMail = new LazyEmail(m, emailAccount, folderName, emailId);
emails.add(newMail);
}
}
} catch (MessagingException e) {
...
} finally {
if (folder != null) {
folder.close(false);
}
if (store != null) {
store.close();
}
}
update(emails);
}
接下来在LazyEmail中,需要时。我正在下载其他电子邮件:
public void updateContentText() {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props, null);
Store store = null;
Folder folder = null;
try {
store = session.getStore("imaps");
store.connect(mEmailAccount.getImapServer(), mEmailAccount.getUsername(),
mEmailAccount.getPassword());
folder = store.getFolder(mFolderName);
folder.open(Folder.READ_ONLY);
// finding email
SearchTerm searchTerm = new MessageIDTerm(mEmailId);
Message[] messages = folder.search(searchTerm);
assert messages.length == 1;
// setting context text
Part mail = messages[0];
if (mail.getContent() instanceof Multipart) {
setContentText((Multipart) mail.getContent());
} else {
setContentText((String) mail.getContent());
}
updateState = UpdateState.CONTENT_TEXT_DOWNLOADED;
} catch (IOException e) {
...
} finally {
if (folder != null) {
folder.close(false);
}
if (store != null) {
store.close();
}
}
}
代码似乎看起来不错。但是当我运行我的Android应用程序时,我收到错误消息[] messages = folder.search(searchTerm);
javax.mail.MessagingException: A4 BAD Execute(): Error in command received;
答案 0 :(得分:0)
您使用的服务器以及JavaMail protocol trace显示的内容是什么?
另请注意,除了信封之外,获取所有这些标题几乎是一种浪费。除非您直接访问原始标头,否则JavaMail将从信封中获取所有信息。
最后,您使用它的方式,没有理由设置“mail.store.protocol”属性。请参阅these common JavaMail mistakes。