/** Returns the body of the message (if it's plain text). */
 public String getBody() throws MessagingException, java.io.IOException {
   Object content = message.getContent();
   if (message.isMimeType("text/plain")) {
     return (String) content;
   } else if (message.isMimeType("multipart/alternative")) {
     Multipart mp = (Multipart) message.getContent();
     int numParts = mp.getCount();
     for (int i = 0; i < numParts; ++i) {
       if (mp.getBodyPart(i).isMimeType("text/plain"))
         return (String) mp.getBodyPart(i).getContent();
     }
     return "";
   } else if (message.isMimeType("multipart/*")) {
     Multipart mp = (Multipart) content;
     if (mp.getBodyPart(0).isMimeType("text/plain"))
       return (String) mp.getBodyPart(0).getContent();
     else return "";
   } else return "";
 }
Example #2
0
 protected int getMessageSize(Message message, Account account)
     throws IOException, MessagingException {
   int count = 0;
   if (account.getLoginName().contains("aol.com") && message.getContent() instanceof Multipart) {
     Multipart multipart = (Multipart) message.getContent();
     for (int i = 0; i < multipart.getCount(); i++) {
       count += multipart.getBodyPart(i).getSize();
     }
   } else {
     count = message.getSize();
   }
   return count;
 }
 /**
  * Saves all attachments to a temp directory, and returns the directory path. Null if no
  * attachments.
  */
 public File saveAttachments(Message message) throws IOException, MessagingException {
   File tmpDir = Files.createTempDir();
   boolean foundAttachments = false;
   Object content = message.getContent();
   if (message.isMimeType(MULTIPART_WILDCARD) && content instanceof Multipart) {
     Multipart mp = (Multipart) content;
     for (int i = 0; i < mp.getCount(); i++) {
       BodyPart bodyPart = mp.getBodyPart(i);
       if (bodyPart instanceof MimeBodyPart && isNotBlank(bodyPart.getFileName())) {
         MimeBodyPart mimeBodyPart = (MimeBodyPart) bodyPart;
         mimeBodyPart.saveFile(new File(tmpDir, mimeBodyPart.getFileName()));
         foundAttachments = true;
       }
     }
   }
   return foundAttachments ? tmpDir : null;
 }
  public static void dumpPart(Part p, biz.systempartners.claims.ClaimsViewer claimsViewer)
      throws Exception {
    if (p instanceof Message) dumpEnvelope((Message) p);

    /**
     * Dump input stream ..
     *
     * <p>InputStream is = p.getInputStream(); // If "is" is not already buffered, wrap a
     * BufferedInputStream // around it. if (!(is instanceof BufferedInputStream)) is = new
     * BufferedInputStream(is); int c; while ((c = is.read()) != -1) System.out.write(c);
     */
    String ct = p.getContentType();
    try {
      pr("CONTENT-TYPE: " + (new ContentType(ct)).toString());
    } catch (ParseException pex) {
      pr("BAD CONTENT-TYPE: " + ct);
    }
    String filename = p.getFileName();
    if (filename != null) pr("FILENAME: " + filename);

    /*
     * Using isMimeType to determine the content type avoids
     * fetching the actual content data until we need it.
     */
    if (p.isMimeType("text/plain")) {
      pr("This is plain text");
      pr("---------------------------");
      if (!showStructure && !saveAttachments) System.out.println((String) p.getContent());
    } else if (p.isMimeType("multipart/*")) {
      pr("This is a Multipart");
      pr("---------------------------");
      Multipart mp = (Multipart) p.getContent();
      level++;
      int count = mp.getCount();
      for (int i = 0; i < count; i++) dumpPart(mp.getBodyPart(i), claimsViewer);
      level--;
    } else if (p.isMimeType("message/rfc822")) {
      pr("This is a Nested Message");
      pr("---------------------------");
      level++;
      dumpPart((Part) p.getContent(), claimsViewer);
      level--;
    } else {
      if (!showStructure && !saveAttachments) {
        /*
         * If we actually want to see the data, and it's not a
         * MIME type we know, fetch it and check its Java type.
         */
        Object o = p.getContent();
        if (o instanceof String) {
          pr("This is a string");
          pr("---------------------------");
          System.out.println((String) o);
        } else if (o instanceof InputStream) {
          pr("This is just an input stream");
          pr("---------------------------");
          InputStream is = (InputStream) o;
          int c;
          while ((c = is.read()) != -1) System.out.write(c);
        } else {
          pr("This is an unknown type");
          pr("---------------------------");
          pr(o.toString());
        }
      } else {
        // just a separator
        pr("---------------------------");
      }
    }

    /*
     * If we're saving attachments, write out anything that
     * looks like an attachment into an appropriately named
     * file.  Don't overwrite existing files to prevent
     * mistakes.
     */
    if (saveAttachments && level != 0 && !p.isMimeType("multipart/*")) {
      String disp = p.getDisposition();
      // many mailers don't include a Content-Disposition
      if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) {
        if (filename == null) filename = "Attachment" + attnum++;
        pr("Saving attachment to file " + filename);
        try {
          File f = new File(System.getProperty("user.dir"), filename);
          /*  if (f.exists())
          // XXX - could try a series of names
          throw new IOException("file exists");*/
          OutputStream os = new BufferedOutputStream(new FileOutputStream(f));
          InputStream is = p.getInputStream();
          int c;
          while ((c = is.read()) != -1) os.write(c);
          os.close();
          if (p.isMimeType("text/xml") || p.isMimeType("application/octet-stream")) {
            processBrRequisitionFile(
                f, claimsViewer, claimsViewer.getInvoiceVector(), claimsViewer.getFilesVector());
          }
          System.out.println("I have saved file [" + f.getAbsolutePath() + "]");
        } catch (IOException ex) {
          pr("Failed to save attachment: " + ex);
        }
        pr("---------------------------");
      }
    }
  }
  public static void readTrainingMail(String fileNameWithPath) {
    InputStream is;

    try {
      is = new FileInputStream(fileNameWithPath);

      Properties props = System.getProperties();
      props.put("mail.host", "stmp.gmail.com");
      props.put("mail.transport.protocol", "stmp");
      Session mailSession = Session.getDefaultInstance(props, null);

      MimeMessage message = new MimeMessage(mailSession, is);

      if (message.getSubject() != null) {
        System.out.println("subject ---> " + message.getSubject());
      }

      if (message.getFrom() != null) {
        System.out.println(message.getFrom()[0].toString());
      }

      /**
       * The Message.RecipientType is divided into TO , the primary recipients -- CC ,carbon copy
       * recipients -- 抄送 BCC, blind carbon copy recipients-- 发送邮件副本,又不想让原始接收人知道,密抄送
       */
      if (message.getRecipients(MimeMessage.RecipientType.CC) != null) {
        System.out.println("CC : found " + message.getRecipients(Message.RecipientType.CC));
      }

      if (message.getRecipients(Message.RecipientType.BCC) != null) {
        System.out.println("BCc : Found " + message.getRecipients(Message.RecipientType.BCC));
      }

      if (message.getRecipients(Message.RecipientType.TO) != null) {
        System.out.println("To Found " + message.getRecipients(Message.RecipientType.TO));
        Address[] AddressList = message.getRecipients(Message.RecipientType.TO);

        for (Address internetAddress : AddressList) {
          InternetAddress addr = (InternetAddress) internetAddress;
          System.out.println(addr.getAddress());
        }
      }

      if (message.getSentDate() != null) {
        System.out.println("message Date : " + message.getSentDate());
      }

      System.out.println("here is the email 's content type name");
      System.out.println(message.getContentType());
      System.out.println("here is the email content ");
      System.out.println(message.getContent());

      if (message.getContentType().startsWith("multipart")) {
        Multipart multiPart = (Multipart) message.getContent();

        for (int x = 0; x < multiPart.getCount(); x++) {
          BodyPart bodyPart = multiPart.getBodyPart(x);
          String disposition = bodyPart.getDisposition();

          if (disposition != null) {
            String content = html2text((String) bodyPart.getContent()).trim();

            System.out.println("Content : " + content);
            System.out.println("disposition " + disposition);
          }

          System.out.println("is email contains disposition ? ");
          if (disposition != null && disposition.equals(BodyPart.ATTACHMENT))
            System.out.println("yes");
          else System.out.println("no");
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /*
   * This method checks for content-type
   * based on which, it processes and
   * fetches the content of the message
   */
  public static void writePart(Part p, MailInfo mailInfo) throws Exception {
    if (p instanceof Message)
      // Call methos writeEnvelope
      writeEnvelope((Message) p, mailInfo);

    log.info("----------------------------");
    log.info("CONTENT-TYPE: " + p.getContentType());

    // check if the content is plain text
    if (p.isMimeType("text/plain")) {
      log.info("This is plain text");
      log.info("---------------------------");
      log.info((String) p.getContent());

      mailInfo.setBody(p.getContent().toString());
    }
    // check if the content has attachment
    else if (p.isMimeType("multipart/*")) {
      log.info("This is a Multipart");
      log.info("---------------------------");
      Multipart mp = (Multipart) p.getContent();
      int count = mp.getCount();
      for (int i = 0; i < count; i++) writePart(mp.getBodyPart(i), mailInfo);
    }
    // check if the content is a nested message
    else if (p.isMimeType("message/rfc822")) {
      log.info("This is a Nested Message");
      log.info("---------------------------");
      writePart((Part) p.getContent(), mailInfo);
    }
    // check if the content is an inline image
    else if (p.isMimeType("image/jpeg")) {
      log.info("--------> image/jpeg");
      Object o = p.getContent();
      InputStream x = (InputStream) o;
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      IOUtils.copy(x, bos);
      NamedContent namedContent = new NamedContent();
      namedContent.setName(p.getFileName());
      namedContent.setType(p.getContentType());
      namedContent.setContent(bos.toByteArray());
      mailInfo.getAttachments().add(namedContent);
    } else if (p.isMimeType("image/png")) {
      log.info("--------> image/png");
      Object o = p.getContent();
      InputStream x = (InputStream) o;
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      IOUtils.copy(x, bos);
      NamedContent namedContent = new NamedContent();
      namedContent.setName(p.getFileName());
      namedContent.setType(p.getContentType());
      namedContent.setContent(bos.toByteArray());
      mailInfo.getAttachments().add(namedContent);
    } else if (p.getContentType().contains("image/")) {
      log.info("content type" + p.getContentType());
      File f = new File("image" + new Date().getTime() + ".jpg");
      DataOutputStream output =
          new DataOutputStream(new BufferedOutputStream(new FileOutputStream(f)));
      com.sun.mail.util.BASE64DecoderStream test =
          (com.sun.mail.util.BASE64DecoderStream) p.getContent();
      byte[] buffer = new byte[1024];
      int bytesRead;
      while ((bytesRead = test.read(buffer)) != -1) {
        output.write(buffer, 0, bytesRead);
      }
    } else {
      Object o = p.getContent();
      if (o instanceof String) {
        log.info("This is a string");
        log.info("---------------------------");
        log.info((String) o);
      } else if (o instanceof InputStream) {
        log.info("This is just an input stream");
        log.info("---------------------------");
        InputStream is = (InputStream) o;
        is = (InputStream) o;
        int c;
        while ((c = is.read()) != -1) System.out.write(c);
      } else {
        log.info("This is an unknown type");
        log.info("---------------------------");
        log.info(o.toString());
      }
    }
  }
Example #7
0
  public static void dumpPart(Part p) throws Exception {
    if (p instanceof Message) {
      Message m = (Message) p;
      Address[] a;
      // FROM
      if ((a = m.getFrom()) != null) {
        for (int j = 0; j < a.length; j++) System.out.println("FROM: " + a[j].toString());
      }

      // TO
      if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
        for (int j = 0; j < a.length; j++) System.out.println("TO: " + a[j].toString());
      }

      // SUBJECT
      System.out.println("SUBJECT: " + m.getSubject());

      // DATE
      Date d = m.getSentDate();
      System.out.println("SendDate: " + (d != null ? d.toLocaleString() : "UNKNOWN"));

      // FLAGS:
      Flags flags = m.getFlags();
      StringBuffer sb = new StringBuffer();
      Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags

      boolean first = true;
      for (int i = 0; i < sf.length; i++) {
        String s;
        Flags.Flag f = sf[i];
        if (f == Flags.Flag.ANSWERED) s = "\\Answered";
        else if (f == Flags.Flag.DELETED) s = "\\Deleted";
        else if (f == Flags.Flag.DRAFT) s = "\\Draft";
        else if (f == Flags.Flag.FLAGGED) s = "\\Flagged";
        else if (f == Flags.Flag.RECENT) s = "\\Recent";
        else if (f == Flags.Flag.SEEN) s = "\\Seen";
        else continue; // skip it
        if (first) first = false;
        else sb.append(' ');
        sb.append(s);
      }

      String[] uf = flags.getUserFlags(); // get the user flag strings
      for (int i = 0; i < uf.length; i++) {
        if (first) first = false;
        else sb.append(' ');
        sb.append(uf[i]);
      }
      System.out.println("FLAGS = " + sb.toString());
    }

    System.out.println("CONTENT-TYPE: " + p.getContentType());

    /* Dump input stream
    InputStream is = ((MimeMessage)m).getInputStream();
    int c;
    while ((c = is.read()) != -1)
        System.out.write(c);
    */

    Object o = p.getContent();
    if (o instanceof String) {
      System.out.println("This is a String");
      System.out.println((String) o);
    } else if (o instanceof Multipart) {
      System.out.println("This is a Multipart");
      Multipart mp = (Multipart) o;
      int count = mp.getCount();
      for (int i = 0; i < count; i++) dumpPart(mp.getBodyPart(i));
    } else if (o instanceof InputStream) {
      System.out.println("This is just an input stream");
      InputStream is = (InputStream) o;
      int c;
      while ((c = is.read()) != -1) System.out.write(c);
    }
  }
  public static List<String> getText(BytesWritable value, Boolean tokenizep)
      throws InterruptedException {
    Session s = Session.getDefaultInstance(new Properties());
    InputStream is = new ByteArrayInputStream(value.getBytes());
    List<String> out = new ArrayList<String>();
    try {
      MimeMessage message = new MimeMessage(s, is);
      message.getAllHeaderLines();

      Analyzer standard_analyzer = new StandardAnalyzer(Version.LUCENE_43);
      Analyzer email_analyzer = new UAX29URLEmailAnalyzer(Version.LUCENE_43);

      Address[] fromAddrs = message.getFrom();
      String fromAddrstr = "";
      if (fromAddrs != null) {
        for (Address addr : fromAddrs) {
          fromAddrstr += (addr.toString() + " ");
        }
      }

      Address[] toAddrs = message.getAllRecipients();
      String toAddrstr = "";
      if (toAddrs != null) {
        for (Address addr : toAddrs) {
          toAddrstr += (addr.toString() + " ");
        }
      }

      String subject = message.getSubject();

      String body = "";
      try {
        Object content = message.getContent();
        // System.err.println(content.getContentType());
        if (content instanceof String) {
          body = (String) content;
        } else if (content instanceof Multipart) {
          Multipart mp = (Multipart) content;
          for (int i = 0; i < mp.getCount(); i++) {
            BodyPart bp = mp.getBodyPart(i);
            // System.err.println(bp.getContentType());
            Object c = bp.getContent();
            if (c instanceof String) {
              body = (String) c;
            }
          }
        }
        // people do really evil things with email, we're not sorting through it all now
      } catch (DecodingException e) {
        System.err.println("DecodingException");
      } catch (UnsupportedEncodingException e) {
        System.err.println("UnsuportedEncodingException");
      } catch (IOException e) {
        System.err.println("IOException");
      }

      if (tokenizep) {
        List<String> fromData = new ArrayList<String>();
        List<String> toData = new ArrayList<String>();
        List<String> subjectData = new ArrayList<String>();
        List<String> bodyData = new ArrayList<String>();

        if (fromAddrstr != null) {
          fromData = tokenizeString(email_analyzer, fromAddrstr);
        }
        if (toAddrstr != null) {
          toData = tokenizeString(email_analyzer, toAddrstr);
        }
        if (subject != null) {
          subjectData = tokenizeString(standard_analyzer, subject);
        }
        if (body != null) {
          bodyData = tokenizeString(standard_analyzer, body);
        }

        out.add("FROM ");
        out.addAll(fromData);

        out.add("TO ");
        out.addAll(toData);

        out.add("SUBJECT ");
        out.addAll(subjectData);

        out.add("BODY ");
        out.addAll(bodyData);
      } else {
        // if not tokenizep, return list with from and subject fields only
        out.add(fromAddrstr);
        out.add(subject);
      }

    } catch (MessagingException e) {
      System.err.println("MessagineException");
    }

    return out;
  }