Advertisement
Guest User

ysad

a guest
May 6th, 2016
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.39 KB | None | 0 0
  1. package de.edv_service_putbus.johannesschumacher.mailparser;
  2.  
  3. import android.util.Log;
  4.  
  5. import com.sun.mail.imap.*;
  6.  
  7. import javax.mail.*;
  8. import javax.mail.search.SearchTerm;
  9.  
  10. import java.io.BufferedReader;
  11. import java.io.IOException;
  12. import java.io.InputStream;
  13. import java.io.InputStreamReader;
  14. import java.util.ArrayList;
  15. import java.util.Arrays;
  16. import java.util.Date;
  17. import java.util.HashMap;
  18. import java.util.List;
  19. import java.util.Properties;
  20. /*
  21.  * Created by Johannes on 14.03.2016.
  22.  *
  23.  * https://sandstorm.de/de/blog/emails-abfragen-per-imap-in-java.html
  24.  */
  25.  
  26. public class Mail {
  27.  
  28.     final static String CLASSNAME = "Mail";
  29.  
  30.     public static HashMap getMails(String url, String username, String password, String[] folderNames, long referenceDate, int count) throws MessagingException {
  31.         Properties props = System.getProperties();
  32.         props.setProperty("mail.store.protocol", "imaps");
  33.         Session session = Session.getDefaultInstance(props, null);
  34.         Store store = session.getStore("imaps");
  35.  
  36.         HashMap<String, List<Protocol>> listDataChild = new HashMap<String, List<Protocol>>();
  37.  
  38.  
  39.         try {
  40.  
  41.             Log.d(CLASSNAME, "Connecting to IMAP-server: " + url);
  42.             store.connect(url, username, password);
  43.  
  44.  
  45.             /*Folder root = store.getDefaultFolder();
  46.             Folder[] folders = root.list();
  47.             Log.d(CLASSNAME, "Folder ausgeben: ");
  48.             for (int i = 0; i < folders.length; i++) {
  49.                 Log.d(CLASSNAME, "\t" + folders[i].getName());
  50.             }*/
  51.  
  52.  
  53.             // run though folders
  54.             for (String folderName : folderNames) {
  55.                 IMAPFolder folder = (IMAPFolder) store.getFolder(folderName);
  56.                 Log.d(CLASSNAME, folderName+ " selected...");
  57.                 listDataChild.put(folderName, readFolder(folder, referenceDate, count));
  58.             }
  59.         } finally {
  60.             store.close();
  61.         }
  62.         return listDataChild;
  63.     }
  64.  
  65.  
  66.     private static List readFolder(IMAPFolder folder, final long referenceDate, final int count) throws MessagingException {
  67.  
  68.         List<Protocol> protocols = new ArrayList<>();
  69.  
  70.         try {
  71.             if (!folder.isOpen()) {
  72.                 folder.open(Folder.READ_ONLY);
  73.             }
  74.  
  75.             // create search criterion
  76.             SearchTerm searchCondition = new SearchTerm() {
  77.                 @Override
  78.                 public boolean match(Message message) {
  79.                     try {
  80.                         if (message.getSentDate().getTime() <= referenceDate) {
  81.                             return true;
  82.                         }
  83.                     } catch (MessagingException e) {
  84.                         Log.e(CLASSNAME, e.getMessage());
  85.                     }
  86.                     return false;
  87.                 }
  88.             };
  89.  
  90.             /*
  91.              * The next line searches for existing messages within the
  92.              * given searchCondition from the server.
  93.              */
  94.             long beforeTime = System.nanoTime();
  95.             Message[] foundMessages = folder.search(searchCondition);
  96.             Log.d(CLASSNAME, "found " + foundMessages.length + " messages (took " + (System.nanoTime() - beforeTime) / 1000 / 1000 + " ms)");
  97.             /*
  98.              * Load some information for latest "count" messages
  99.              * with one single request to save some time here.
  100.              */
  101.             beforeTime = System.nanoTime();
  102.             Message[] messages = Arrays.copyOfRange(foundMessages, Math.max(0, foundMessages.length - count), foundMessages.length);
  103.             // this instance could be created outside the loop as well
  104.             FetchProfile metadataProfile = new FetchProfile();
  105.             // load From, To, Cc, Bcc, ReplyTo, Subject and Date
  106.             metadataProfile.add(FetchProfile.Item.ENVELOPE);
  107.             // load the entire messages (headers and body, including all "attachments")
  108.             metadataProfile.add(IMAPFolder.FetchProfileItem.MESSAGE);
  109.             folder.fetch(messages, metadataProfile);
  110.             Log.d(CLASSNAME, "loading messages (took " + (System.nanoTime() - beforeTime) / 1000 / 1000 + " ms)");
  111.  
  112.             /*
  113.              * Now that we have all the information we need, print some mails.
  114.              */
  115.             beforeTime = System.nanoTime();
  116.             for (int i = messages.length - 1; i >= 0; i--) {
  117.                 Message message = messages[i];
  118.                 long uid = folder.getUID(message);
  119.  
  120.                 protocols.add(new Protocol(uid, message.getSubject(), message.getSentDate(), getAttachment(message)));
  121.                 Log.d(CLASSNAME, "\t" + uid + "\t" + message.getSentDate() + "\t" + message.getSubject());
  122.             }
  123.             Log.d(CLASSNAME, "list messages (took " + (System.nanoTime() - beforeTime) / 1000 / 1000 + " ms)");
  124.  
  125.         } finally {
  126.             if (folder.isOpen()) {
  127.                 folder.close(true);
  128.             }
  129.         }
  130.         return protocols;
  131.     }
  132.  
  133.  
  134.     private static String getAttachment(Message message) throws MessagingException {
  135.         // Search for Attachmentpart in Email and build a String to parse
  136.         StringBuilder stringBuilder = new StringBuilder();
  137.         String line;
  138.  
  139.         try {
  140.             Multipart multipart;
  141.             // check content for right instance, might be String
  142.             if (message.getContent() instanceof Multipart) {
  143.                 multipart = (Multipart) message.getContent();
  144.  
  145.                 for (int i = 0; i < multipart.getCount(); i++) {
  146.                     BodyPart bodyPart = multipart.getBodyPart(i);
  147.                     if (Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && bodyPart.isMimeType("text/plain")) {
  148.                         InputStream inputStream = bodyPart.getInputStream();
  149.                         if (inputStream != null) {
  150.                             try {
  151.                                 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
  152.                                 while ((line = reader.readLine()) != null) {
  153.                                     stringBuilder.append(line);
  154.                                     stringBuilder.append("\n");
  155.                                 }
  156.                             } finally {
  157.                                 inputStream.close();
  158.                             }
  159.                             return stringBuilder.toString();
  160.                         }
  161.                     }
  162.                 }
  163.             }
  164.         } catch (IOException e) {
  165.             Log.e(CLASSNAME, e.getMessage());
  166.         }
  167.         return "";
  168.     }
  169.  
  170.     /*
  171.      * algorithm to find closest Message for a referenceDate
  172.      */
  173.     private Message findClosestUID(Message[] messages, long referenceDate) throws MessagingException {
  174.         int begin = 0, end = messages.length-1, left = end / 2, right = left + 1;
  175.  
  176.         if (messages.length > 1) {
  177.             while (begin - end != 0) {
  178.                 if (Math.abs(referenceDate - messages[left].getSentDate().getTime()) <
  179.                         Math.abs(referenceDate - messages[right].getSentDate().getTime())) {
  180.                     end = left;
  181.                 } else {
  182.                     begin = right;
  183.                 }
  184.                 left = (end - begin) / 2 +begin;
  185.                 right = left+1;
  186.             }
  187.         }
  188.         return messages[begin];
  189.     }
  190. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement