Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package de.edv_service_putbus.johannesschumacher.mailparser;
- import android.util.Log;
- import com.sun.mail.imap.*;
- import javax.mail.*;
- import javax.mail.search.SearchTerm;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Properties;
- /*
- * Created by Johannes on 14.03.2016.
- *
- * https://sandstorm.de/de/blog/emails-abfragen-per-imap-in-java.html
- */
- public class Mail {
- final static String CLASSNAME = "Mail";
- public static HashMap getMails(String url, String username, String password, String[] folderNames, long referenceDate, int count) throws MessagingException {
- Properties props = System.getProperties();
- props.setProperty("mail.store.protocol", "imaps");
- Session session = Session.getDefaultInstance(props, null);
- Store store = session.getStore("imaps");
- HashMap<String, List<Protocol>> listDataChild = new HashMap<String, List<Protocol>>();
- try {
- Log.d(CLASSNAME, "Connecting to IMAP-server: " + url);
- store.connect(url, username, password);
- /*Folder root = store.getDefaultFolder();
- Folder[] folders = root.list();
- Log.d(CLASSNAME, "Folder ausgeben: ");
- for (int i = 0; i < folders.length; i++) {
- Log.d(CLASSNAME, "\t" + folders[i].getName());
- }*/
- // run though folders
- for (String folderName : folderNames) {
- IMAPFolder folder = (IMAPFolder) store.getFolder(folderName);
- Log.d(CLASSNAME, folderName+ " selected...");
- listDataChild.put(folderName, readFolder(folder, referenceDate, count));
- }
- } finally {
- store.close();
- }
- return listDataChild;
- }
- private static List readFolder(IMAPFolder folder, final long referenceDate, final int count) throws MessagingException {
- List<Protocol> protocols = new ArrayList<>();
- try {
- if (!folder.isOpen()) {
- folder.open(Folder.READ_ONLY);
- }
- // create search criterion
- SearchTerm searchCondition = new SearchTerm() {
- @Override
- public boolean match(Message message) {
- try {
- if (message.getSentDate().getTime() <= referenceDate) {
- return true;
- }
- } catch (MessagingException e) {
- Log.e(CLASSNAME, e.getMessage());
- }
- return false;
- }
- };
- /*
- * The next line searches for existing messages within the
- * given searchCondition from the server.
- */
- long beforeTime = System.nanoTime();
- Message[] foundMessages = folder.search(searchCondition);
- Log.d(CLASSNAME, "found " + foundMessages.length + " messages (took " + (System.nanoTime() - beforeTime) / 1000 / 1000 + " ms)");
- /*
- * Load some information for latest "count" messages
- * with one single request to save some time here.
- */
- beforeTime = System.nanoTime();
- Message[] messages = Arrays.copyOfRange(foundMessages, Math.max(0, foundMessages.length - count), foundMessages.length);
- // this instance could be created outside the loop as well
- FetchProfile metadataProfile = new FetchProfile();
- // load From, To, Cc, Bcc, ReplyTo, Subject and Date
- metadataProfile.add(FetchProfile.Item.ENVELOPE);
- // load the entire messages (headers and body, including all "attachments")
- metadataProfile.add(IMAPFolder.FetchProfileItem.MESSAGE);
- folder.fetch(messages, metadataProfile);
- Log.d(CLASSNAME, "loading messages (took " + (System.nanoTime() - beforeTime) / 1000 / 1000 + " ms)");
- /*
- * Now that we have all the information we need, print some mails.
- */
- beforeTime = System.nanoTime();
- for (int i = messages.length - 1; i >= 0; i--) {
- Message message = messages[i];
- long uid = folder.getUID(message);
- protocols.add(new Protocol(uid, message.getSubject(), message.getSentDate(), getAttachment(message)));
- Log.d(CLASSNAME, "\t" + uid + "\t" + message.getSentDate() + "\t" + message.getSubject());
- }
- Log.d(CLASSNAME, "list messages (took " + (System.nanoTime() - beforeTime) / 1000 / 1000 + " ms)");
- } finally {
- if (folder.isOpen()) {
- folder.close(true);
- }
- }
- return protocols;
- }
- private static String getAttachment(Message message) throws MessagingException {
- // Search for Attachmentpart in Email and build a String to parse
- StringBuilder stringBuilder = new StringBuilder();
- String line;
- try {
- Multipart multipart;
- // check content for right instance, might be String
- if (message.getContent() instanceof Multipart) {
- multipart = (Multipart) message.getContent();
- for (int i = 0; i < multipart.getCount(); i++) {
- BodyPart bodyPart = multipart.getBodyPart(i);
- if (Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && bodyPart.isMimeType("text/plain")) {
- InputStream inputStream = bodyPart.getInputStream();
- if (inputStream != null) {
- try {
- BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
- while ((line = reader.readLine()) != null) {
- stringBuilder.append(line);
- stringBuilder.append("\n");
- }
- } finally {
- inputStream.close();
- }
- return stringBuilder.toString();
- }
- }
- }
- }
- } catch (IOException e) {
- Log.e(CLASSNAME, e.getMessage());
- }
- return "";
- }
- /*
- * algorithm to find closest Message for a referenceDate
- */
- private Message findClosestUID(Message[] messages, long referenceDate) throws MessagingException {
- int begin = 0, end = messages.length-1, left = end / 2, right = left + 1;
- if (messages.length > 1) {
- while (begin - end != 0) {
- if (Math.abs(referenceDate - messages[left].getSentDate().getTime()) <
- Math.abs(referenceDate - messages[right].getSentDate().getTime())) {
- end = left;
- } else {
- begin = right;
- }
- left = (end - begin) / 2 +begin;
- right = left+1;
- }
- }
- return messages[begin];
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement