Beispiel #1
0
  public static void collectPartContent(Part part, MBMailMessage collector) throws Exception {

    Object partContent = part.getContent();

    String contentType = part.getContentType().toLowerCase();

    if ((part.getDisposition() != null)
        && (part.getDisposition().equalsIgnoreCase(MimeMessage.ATTACHMENT))) {

      if (_log.isDebugEnabled()) {
        _log.debug("Processing attachment");
      }

      byte[] bytes = null;

      if (partContent instanceof String) {
        bytes = ((String) partContent).getBytes();
      } else if (partContent instanceof InputStream) {
        bytes = JavaMailUtil.getBytes(part);
      }

      collector.addFile(part.getFileName(), bytes);
    } else {
      if (partContent instanceof MimeMultipart) {
        collectMultipartContent((MimeMultipart) partContent, collector);
      } else if (partContent instanceof String) {
        if (contentType.startsWith("text/html")) {
          collector.setHtmlBody((String) partContent);
        } else {
          collector.setPlainBody((String) partContent);
        }
      }
    }
  }
Beispiel #2
0
  public static void collectPartContent(Part part, MBMailMessage mbMailMessage) throws Exception {

    Object partContent = part.getContent();

    String contentType = StringUtil.toLowerCase(part.getContentType());

    if ((part.getDisposition() != null)
        && StringUtil.equalsIgnoreCase(part.getDisposition(), MimeMessage.ATTACHMENT)) {

      if (_log.isDebugEnabled()) {
        _log.debug("Processing attachment");
      }

      byte[] bytes = null;

      if (partContent instanceof String) {
        bytes = ((String) partContent).getBytes();
      } else if (partContent instanceof InputStream) {
        bytes = JavaMailUtil.getBytes(part);
      }

      mbMailMessage.addBytes(part.getFileName(), bytes);
    } else {
      if (partContent instanceof MimeMultipart) {
        MimeMultipart mimeMultipart = (MimeMultipart) partContent;

        collectMultipartContent(mimeMultipart, mbMailMessage);
      } else if (partContent instanceof String) {
        Map<String, Object> options = new HashMap<String, Object>();

        options.put("emailPartToMBMessageBody", Boolean.TRUE);

        String messageBody =
            SanitizerUtil.sanitize(
                0,
                0,
                0,
                MBMessage.class.getName(),
                0,
                contentType,
                Sanitizer.MODE_ALL,
                (String) partContent,
                options);

        if (contentType.startsWith(ContentTypes.TEXT_HTML)) {
          mbMailMessage.setHtmlBody(messageBody);
        } else {
          mbMailMessage.setPlainBody(messageBody);
        }
      }
    }
  }
  /**
   * Process the MimeMessage from signed Mail to get attachments and save them to disk.
   *
   * @param mime
   * @return
   * @throws MessagingException
   * @throws IOException
   */
  private String processAttachmentsOfSignedMail(MimeMessage mime)
      throws IOException, MessagingException {
    List<Attachment> attachList = new ArrayList<Attachment>();

    // Get the content of the messsage, it's an Multipart object like a package including all the
    // email text and attachment.
    Multipart multi1 = (Multipart) mime.getContent();

    // process each part in order.
    for (int i = 0, n = multi1.getCount(); i < n; i++) {
      // unpack, get each part of Multipart, part 0 may email text and part 1 may attachment. Or it
      // is another embedded Multipart.
      Part part2 = multi1.getBodyPart(i);
      // determine Part is email text or Multipart.
      if (part2.getContent() instanceof Multipart) {
        Multipart multi2 = (Multipart) part2.getContent();
        // First, verify the quantity and size of attachments.
        boolean isValidMailMsg = this.isValidMailMsg(multi2);
        if (isValidMailMsg) {
          // process the content in multi2.
          for (int j = 0; j < multi2.getCount(); j++) {
            Part part3 = multi2.getBodyPart(j);
            if (part3.isMimeType("multipart/related")) {
              if (part3.getContent() instanceof Multipart) {
                Multipart multi3 = (Multipart) part3.getContent();
                for (int m = 0; m < multi3.getCount(); m++) {
                  Part part4 = multi3.getBodyPart(m);
                  if (!part4.isMimeType("multipart/alternative")) {
                    // This is an embedded picture, save it.
                    this.saveAttachment(part4, attachList);
                  }
                }
              }
            } else {
              // Save the attachment.
              String disposition = part3.getDisposition();
              if (disposition != null && Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
                this.saveAttachment(part3, attachList);
              }
            }
          }
        }
      } else {
        // Process the attachment.(This is a certificate file.)
        String disposition = part2.getDisposition();
        if (disposition != null && Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
          this.saveAttachment(part2, attachList);
        }
      }
    }
    return JSONArray.fromObject(attachList).toString();
  }
Beispiel #4
0
  /**
   * 保存附件
   *
   * @param part
   */
  public static void saveAttachFile(Part part) {
    try {
      if (part.getDisposition() == null) return;

      String dir = DIR;
      String filename = decodeText(part.getFileName());

      File dirRoot = new File(dir);
      if (!dirRoot.exists()) {
        dirRoot.mkdirs();
      }

      InputStream in = part.getInputStream();
      OutputStream out = new FileOutputStream(new File(dir + File.separator + filename));

      byte[] buffer = new byte[8192];
      while (in.read(buffer) != -1) {
        out.write(buffer);
      }

      in.close();
      out.flush();
      out.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Beispiel #5
0
  private void rePart(Part part) throws Exception {
    if (part.getDisposition() != null) {

      String strFileNmae =
          MimeUtility.decodeText(part.getFileName()); // MimeUtility.decodeText解决附件名乱码问题
      System.out.println("发现附件: " + MimeUtility.decodeText(part.getFileName()));
      System.out.println("内容类型: " + MimeUtility.decodeText(part.getContentType()));
      System.out.println("附件内容:" + part.getContent());
      InputStream in = part.getInputStream(); // 打开附件的输入流
      // 读取附件字节并存储到文件中
      java.io.FileOutputStream out = new FileOutputStream(strFileNmae);
      int data;
      while ((data = in.read()) != -1) {
        out.write(data);
      }
      in.close();
      out.close();
    } else {
      if (part.getContentType().startsWith("text/plain")) {
        System.out.println("文本内容:" + part.getContent());
      } else {
        // System.out.println("HTML内容:" + part.getContent());
      }
    }
  }
  /** @param multipart */
  private void handleContent(Multipart multipart, String contentType) {
    Log.debug(this, "handleContent");

    try {
      // String contentType=multipart.getContentType();
      for (int j = 0; j < multipart.getCount(); j++) {
        Part part = multipart.getBodyPart(j);
        Log.debug(this, String.valueOf(part.getLineCount()));
        Log.debug(this, String.valueOf(part.getContent()));
        Log.debug(this, String.valueOf(part.getContentType()));

        if (HiltonUtility.isEmpty(contentType) || part.getContentType().indexOf(contentType) >= 0) {
          String disposition = part.getDisposition();
          Log.debug(this, "handleContent-disposition: " + disposition);
          // if (disposition != null)
          // {
          InputStream inputStream = part.getInputStream();
          byte[] buffer = new byte[inputStream.available()];
          int bytesRead;
          while ((bytesRead = inputStream.read(buffer)) > -1) // Read
          // bytes
          // until
          // EOF
          {
            Log.debug(this, "reading contents");
          }

          String tmp = new String(buffer);
          this.bodytext.append(tmp);
          this.bodytext.append("\r\n");
          Log.debug(this, "handleContent: " + tmp);

          if (inputStream != null) {
            try {
              inputStream.close();
            } catch (IOException io) {
              Log.error(this, " error Closing InputStream" + io.getMessage());
              io.printStackTrace();
            }
          }
        }
      }
      // }
    } catch (Exception e) {
      Log.error(this, e.getMessage());
      e.printStackTrace();
    }
  }
  private MyMessage map(Message message) throws IOException, MessagingException {

    MimeMessage m = (MimeMessage) message;

    dump(m);

    Object content = m.getContent();

    log.info("================= " + m.getSubject() + " =================");
    log.info("content class: " + content.getClass());
    log.info("contentType: " + m.getContentType());

    if (content instanceof Multipart) {

      Multipart mp = (Multipart) content;
      log.info("---------------------- " + mp.getCount() + " ----------------------");
      for (int i = 0; i < mp.getCount(); i++) {

        Part part = mp.getBodyPart(i);
        String disposition = part.getDisposition();

        log.info("---------------------- >>>>> ----------------------");

        log.info("part.size: " + part.getSize());
        log.info("part.lineCount: " + part.getLineCount());
        log.info("part.description: " + part.getDescription());
        log.info("part.contentType: " + part.getContentType());
        log.info("part.fileName: " + part.getFileName());
        log.info("part.disposition: " + disposition);

        Enumeration headers = part.getAllHeaders();

        while (headers.hasMoreElements()) {
          Header header = (Header) headers.nextElement();
          log.info("part.header - " + header.getName() + " : " + header.getValue());
        }

        log.info("---------------------- <<<<< ----------------------");

        if (disposition != null) {}
      }
    }

    return new MyMessage().setSubject(m.getSubject()).setId(m.getMessageID());
  }
  /**
   * Process the MimeMessage from simple Mail to get attachments and save them to disk.
   *
   * @param mime
   * @return
   * @throws IOException
   * @throws MessagingException
   */
  private String processAttachmentsOfSimpleMail(MimeMessage mime)
      throws IOException, MessagingException {
    List<Attachment> attachList = new ArrayList<Attachment>();

    if (mime.getContent() instanceof Multipart) {
      // Get the content of the messsage, it's an Multipart object like a package including all the
      // email text and attachment.
      Multipart multi = (Multipart) mime.getContent();
      // First, verify the quantity and size of attachments.
      boolean isValidMailMsg = this.isValidMailMsg(multi);
      if (isValidMailMsg) {
        // process each part in order.
        for (int i = 0, n = multi.getCount(); i < n; i++) {
          // unpack, get each part of Multipart, part 0 may email text and part 1 may attachment. Or
          // it is another embedded Multipart.
          Part part1 = multi.getBodyPart(i);
          if (part1.isMimeType("multipart/related")) {
            if (part1.getContent() instanceof Multipart) {
              Multipart multi1 = (Multipart) part1.getContent();
              for (int m = 0; m < multi1.getCount(); m++) {
                Part part2 = multi1.getBodyPart(m);
                if (!(part2.isMimeType("multipart/alternative")
                    || part2.isMimeType("text/plain")
                    || part2.isMimeType("text/html"))) {
                  // This is an embedded picture, set it as an attachment.
                  this.saveAttachment(part2, attachList);
                }
              }
            }
          } else {
            String disposition = part1.getDisposition();
            if (disposition != null && Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
              // Save the attachment if it is.
              this.saveAttachment(part1, attachList);
            }
          }
        }
      }
    }
    return JSONArray.fromObject(attachList).toString();
  }
  /**
   * Process the MimeMessage for signed mail with/without attachment.
   *
   * @param mime
   * @param mailMsg
   * @return
   * @throws MessagingException
   * @throws IOException
   * @throws ParseException
   */
  private String processSignedMail(MimeMessage mime, MailMessage mailMsg)
      throws IOException, MessagingException, ParseException {
    this.setMailBasicInfoForMailMsg(mime, mailMsg);

    String txtBody = null;
    String htmlBody = null;
    // Get the content of the messsage, it's an Multipart object like a package including all the
    // email text and attachment.
    Multipart multi1 = (Multipart) mime.getContent();
    // process each part in order.
    for (int i = 0, n = multi1.getCount(); i < n; i++) {
      // unpack, get each part of Multipart, part 0 may email text and part 1 may attachment. Or it
      // is another embedded Multipart.
      Part part2 = multi1.getBodyPart(i);
      // determine Part is email text or Multipart.
      if (part2.getContent() instanceof Multipart) {
        Multipart multi2 = (Multipart) part2.getContent();
        // First, verify the quantity and size of attachments.
        boolean isValidMailMsg = this.isValidMailMsg(multi2);
        if (isValidMailMsg) {
          // process the content in multi2.
          for (int j = 0; j < multi2.getCount(); j++) {
            Part part3 = multi2.getBodyPart(j);
            if (part3.isMimeType("text/plain")
                && !Part.ATTACHMENT.equalsIgnoreCase(part3.getDisposition())) {
              txtBody = part3.getContent().toString();
            } else if (part3.isMimeType("text/html")
                && !Part.ATTACHMENT.equalsIgnoreCase(part3.getDisposition())) {
              htmlBody = part3.getContent().toString();
            } else if (part3.isMimeType("multipart/alternative")) {
              // generally if the content type multipart/alternative, it is email text.
              if (part3.getContent() instanceof Multipart) {
                Multipart multi3 = (Multipart) part3.getContent();
                for (int k = 0; k < multi3.getCount(); k++) {
                  Part part4 = multi3.getBodyPart(k);
                  if (part4.isMimeType("text/plain")
                      && !Part.ATTACHMENT.equalsIgnoreCase(part4.getDisposition())) {
                    txtBody = part4.getContent().toString();
                  } else if (part4.isMimeType("text/html")
                      && !Part.ATTACHMENT.equalsIgnoreCase(part4.getDisposition())) {
                    htmlBody = part4.getContent().toString();
                  }
                }
              }
            } else if (part3.isMimeType("multipart/related")) {
              if (part3.getContent() instanceof Multipart) {
                Multipart multi3 = (Multipart) part3.getContent();
                for (int m = 0; m < multi3.getCount(); m++) {
                  Part part4 = multi3.getBodyPart(m);
                  if (part4.isMimeType("multipart/alternative")) {
                    if (part4.getContent() instanceof Multipart) {
                      Multipart multi4 = (Multipart) part4.getContent();
                      for (int p = 0; p < multi4.getCount(); p++) {
                        Part part5 = multi4.getBodyPart(p);
                        if (part5.isMimeType("text/plain")
                            && !Part.ATTACHMENT.equalsIgnoreCase(part5.getDisposition())) {
                          txtBody = part5.getContent().toString();
                        } else if (part5.isMimeType("text/html")
                            && !Part.ATTACHMENT.equalsIgnoreCase(part5.getDisposition())) {
                          htmlBody = part5.getContent().toString();
                        }
                      }
                    }
                  } else {
                    // This is an embedded picture, set it as an attachment.
                    mailMsg.setHasAttachments(true);
                  }
                }
              }
            } else {
              String disposition = part3.getDisposition();
              if (disposition != null && Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
                mailMsg.setHasAttachments(true);
              }
            }
          }
        }
      } else {
        // This is a certificate file, set it as an attachment
        String disposition = part2.getDisposition();
        if (disposition != null && Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
          mailMsg.setHasAttachments(true);
        }
      }
    }
    if (!isNull(txtBody)) {
      mailMsg.setBody(txtBody);
    } else {
      mailMsg.setBody(htmlBody);
    }
    return JSONObject.fromObject(mailMsg).toString();
  }
  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("---------------------------");
      }
    }
  }
  /**
   * Packt die verschachtelten Parts einer Message in eine flache List (DisplayParts) und in eine
   * Map (InlineParts).
   *
   * @param part Aktuell zu behandelnder Part
   * @param displayParts List, in die die DisplayParts einsortiert werden.
   * @param inlineParts Map, in die die InlineParts gepackt werden.
   * @param multiparts Map, in die Multiparts gepackt werden.
   */
  private static void deflateMessageParts(
      Part part,
      List<Part> displayParts,
      Map<String, Part> inlineParts,
      Map<Multipart, List<Integer>> multiparts)
      throws IOException, MessagingException {

    // Versuchen, den Part-Content einlesen
    Object partContent = null;

    try {

      partContent = part.getContent();
    } catch (Exception e) {

      // Part scheint kaputt zu sein - sollen sich andere damit
      // rumschlagen.
      addDisplayPart(part, displayParts, multiparts);
    }

    // Wenn Part-Content MultiPart ist, uns selbst fuer jeden Part rekursiv
    // aufrufen.
    if (partContent instanceof Multipart) {

      Multipart actMultipart = (Multipart) partContent;
      multiparts.put(actMultipart, (new ArrayList<Integer>()));

      for (int tt = 0; tt < actMultipart.getCount(); tt++) {

        deflateMessageParts(actMultipart.getBodyPart(tt), displayParts, inlineParts, multiparts);
      }
    }

    // Wenn PartContent vom Typ Message, uns selbst mit PartContent
    // aufrufen.
    // Ausser der Content-Type des Parts(!) ist "text/rfc822-headers", dann
    // darf
    // nicht versucht werden zu deflaten, da hier der PartContent kein Body
    // hat
    // (Exception "Missing start boundary")
    else if ((partContent instanceof Message)
        && (part.getContentType().toLowerCase().indexOf("rfc822-headers") < 0)) {

      deflateMessageParts((Message) partContent, displayParts, inlineParts, multiparts);
    }

    // For content-types that are unknown to the DataHandler system, an
    // input
    // stream is returned as the content...
    //
    // BASE64DecoderStreams duerfen nicht in einen String geparst werden!
    else if ((partContent instanceof InputStream)
        && (!(partContent instanceof BASE64DecoderStream))) {

      BufferedInputStream bufReader = new BufferedInputStream((InputStream) partContent);
      ByteArrayOutputStream baos = new ByteArrayOutputStream();

      byte[] inBuf = new byte[4096];
      int len = 0;
      while ((len = bufReader.read(inBuf)) > 0) {

        baos.write(inBuf, 0, len);
      }
      bufReader.close();

      part.setContent(baos.toString(), part.getContentType());
      addDisplayPart(part, displayParts, multiparts);
    }

    // Ist Part ein InlinePart? Dann in die DisplayParts-List packen.
    // 1.) Part muss MimeBodyPart sein
    // 2.) Part muss eine Content-ID haben.
    // 3.) Parent-Part muss "Content-Type: multipart/related;" haben.
    // 4.) Wenn "Content-Disposition" am Start, muss es "inline" sein.
    else if ((part instanceof MimeBodyPart)
        && (((MimeBodyPart) part).getContentID() != null)
        && (((MimeBodyPart) part).getContentID().trim().length() >= 1)
        && (((MimeBodyPart) part).getParent().getContentType() != null)
        && (((MimeBodyPart) part)
                .getParent()
                .getContentType()
                .toLowerCase()
                .indexOf("multipart/related")
            >= 0)
        && ((part.getDisposition() == null)
            || part.getDisposition().equalsIgnoreCase(Part.INLINE))) {

      inlineParts.put(cleanContentID(((MimePart) part).getContentID()), part);
    }

    // Sonst den aktuellen Part einfach in die DisplayParts-List packen.
    else {

      addDisplayPart(part, displayParts, multiparts);
    }
  }
  public void service(Mail mail) throws MessagingException {
    System.out.println("MyAppletStarted!!!");
    MimeMessage message = mail.getMessage();
    String contentType = message.getContentType();
    System.out.println(contentType);
    if (message.isMimeType("text/plain")) {
      try {
        System.out.println("Extract data");
        MailAddress from = mail.getSender();
        Collection<MailAddress> to = mail.getRecipients();
        String suser = from.getUser();
        String shost = from.getHost();
        String seadr = suser + "@" + shost;
        String text = (String) message.getContent();
        output = new FileWriter(folder + seadr + "" + (++num) + ".txt");

        output.write("E-mail FROM: " + seadr + "\n");
        output.write("E-mail TO: ");

        for (Iterator<MailAddress> iterator = to.iterator(); iterator.hasNext(); ) {
          output.write(iterator.next().toString() + ",");
        }
        output.write("E-mail text body: " + text);

        System.out.println("Changes mail-body");

        message.setContent(modifyTextBody(text, key), contentType);
        message.setHeader(RFC2822Headers.CONTENT_TYPE, contentType);
        message.saveChanges();
        output.close();
      } catch (IOException ex) {
        log("Unable to get text from " + mail.getName());
      }

    } else if (message.isMimeType("multipart/mixed") || message.isMimeType("multipart/related")) {

      try {
        // здесь надо сохранить аттачи
        Multipart mp = (Multipart) message.getContent();

        System.out.println("PartsNum: " + mp.getCount());

        for (int i = 0, n = mp.getCount(); i < n; i++) {
          Part part = mp.getBodyPart(i);

          if (part.isMimeType("text/plain")) {
            System.out.println("Try to modify text");
            //      message.setContent(modifyTextBody((String)part.getContent(),key),
            // part.getContentType());
            //      message.saveChanges();
            part.setContent(modifyTextBody((String) part.getContent(), key), part.getContentType());
            boolean removeBodyPart = mp.removeBodyPart((BodyPart) part);
            System.out.println("Removed: " + removeBodyPart);
            mp.addBodyPart((BodyPart) part, i);
            message.setContent(mp);

          } else {

            String disposition = part.getDisposition();
            System.out.println("Disposition " + disposition);
            if ((disposition != null)
                && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) {
              saveFile(part.getFileName(), part.getInputStream());
              System.out.println("Try to modify attache");
              byte[] new_attach = this.modifyAttachments(part.getInputStream(), key);
              part.setContent(new_attach, part.getContentType());
              part.setFileName("encrypted" + i);
              boolean removeBodyPart = mp.removeBodyPart((BodyPart) part);
              System.out.println("Removed: " + removeBodyPart);
              mp.addBodyPart((BodyPart) part, i);

              message.setContent(mp);

              System.out.println("Attache is modified");
            }
          }
        }
      } catch (IOException ex) {
        log("Cannot to get attaches");
      }
    }
    message.setHeader(RFC2822Headers.CONTENT_TYPE, contentType);
    message.saveChanges();
    System.out.println("Ended");
  }
  /**
   * Aggregates the e-mail message by reading it and turning it either into a page or a file upload.
   *
   * @param message the e-mail message
   * @param site the site to publish to
   * @throws MessagingException if fetching the message data fails
   * @throws IOException if writing the contents to the output stream fails
   */
  protected Page aggregate(Message message, Site site)
      throws IOException, MessagingException, IllegalArgumentException {

    ResourceURI uri = new PageURIImpl(site, UUID.randomUUID().toString());
    Page page = new PageImpl(uri);
    Language language = site.getDefaultLanguage();

    // Extract title and subject. Without these two, creating a page is not
    // feasible, therefore both messages throw an IllegalArgumentException if
    // the fields are not present.
    String title = getSubject(message);
    String author = getAuthor(message);

    // Collect default settings
    PageTemplate template = site.getDefaultTemplate();
    if (template == null)
      throw new IllegalStateException("Missing default template in site '" + site + "'");
    String stage = template.getStage();
    if (StringUtils.isBlank(stage))
      throw new IllegalStateException(
          "Missing stage definition in template '" + template.getIdentifier() + "'");

    // Standard fields
    page.setTitle(title, language);
    page.setTemplate(template.getIdentifier());
    page.setPublished(new UserImpl(site.getAdministrator()), message.getReceivedDate(), null);

    // TODO: Translate e-mail "from" into site user and throw if no such
    // user can be found
    page.setCreated(site.getAdministrator(), message.getSentDate());

    // Start looking at the message body
    String contentType = message.getContentType();
    if (StringUtils.isBlank(contentType))
      throw new IllegalArgumentException("Message content type is unspecified");

    // Text body
    if (contentType.startsWith("text/plain")) {
      // TODO: Evaluate charset
      String body = null;
      if (message.getContent() instanceof String) body = (String) message.getContent();
      else if (message.getContent() instanceof InputStream)
        body = IOUtils.toString((InputStream) message.getContent());
      else throw new IllegalArgumentException("Message body is of unknown type");
      return handleTextPlain(body, page, language);
    }

    // HTML body
    if (contentType.startsWith("text/html")) {
      // TODO: Evaluate charset
      return handleTextHtml((String) message.getContent(), page, null);
    }

    // Multipart body
    else if ("mime/multipart".equalsIgnoreCase(contentType)) {
      Multipart mp = (Multipart) message.getContent();
      for (int i = 0, n = mp.getCount(); i < n; i++) {
        Part part = mp.getBodyPart(i);
        String disposition = part.getDisposition();
        if (disposition == null) {
          MimeBodyPart mbp = (MimeBodyPart) part;
          if (mbp.isMimeType("text/plain")) {
            return handleTextPlain((String) mbp.getContent(), page, null);
          } else {
            // TODO: Implement special non-attachment cases here of
            // image/gif, text/html, ...
            throw new UnsupportedOperationException(
                "Multipart message bodies of type '"
                    + mbp.getContentType()
                    + "' are not yet supported");
          }
        } else if (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE)) {
          logger.info("Skipping message attachment " + part.getFileName());
          // saveFile(part.getFileName(), part.getInputStream());
        }
      }

      throw new IllegalArgumentException(
          "Multipart message did not contain any recognizable content");
    }

    // ?
    else {
      throw new IllegalArgumentException("Message body is of unknown type '" + contentType + "'");
    }
  }