예제 #1
0
  public static String getText(Part part) {

    try {
      ContentType contentType = new ContentType(part.getContentType());
      System.err.println(
          "contentType: "
              + part.getContentType()
              + ", class: "
              + part.getContent().getClass().getName());

      if (part.isMimeType("text/*")) {
        String charset = contentType.getParameter("charset");
        System.err.println("Charset: " + charset);

        return (String) part.getContent();

      } else if (part.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) part.getContent();
        for (int i = 0; i < mp.getCount(); i++) {
          String text = getText(mp.getBodyPart(i));

          if (text != null) {
            return text;
          }
        }
      }
      return null;
    } catch (ParseException e) {
      throw new RuntimeException(e);
    } catch (MessagingException e) {
      throw new RuntimeException(e);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
예제 #2
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());
      }
    }
  }
예제 #3
0
  /** @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();
    }
  }
예제 #4
0
  private static Attachment saveAttachment(Part partToAttach, Resource container)
      throws MessagingException, IOException, NoSuchAlgorithmException {
    Attachment attach = new Attachment();
    String fileName = MimeUtility.decodeText(partToAttach.getFileName());
    attach.store(partToAttach.getInputStream(), fileName, container);
    if (!attach.mimeType.equalsIgnoreCase(partToAttach.getContentType())) {
      Logger.info(
          "The email says the content type is '"
              + partToAttach.getContentType()
              + "' but Yobi determines it is '"
              + attach.mimeType
              + "'");
    }

    return attach;
  }
예제 #5
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);
        }
      }
    }
  }
예제 #6
0
 private static String getBody(Part msg, String contentType)
     throws MessagingException, IOException, SAXException {
   if (msg.getContentType().startsWith(contentType)) {
     return msg.getContent().toString();
   } else if (msg.getContentType().startsWith("multipart/")) {
     MimeMultipart multi = (MimeMultipart) msg.getContent();
     for (int i = 0; i < multi.getCount(); i++) {
       BodyPart part = multi.getBodyPart(i);
       String content = getBody(part);
       if (content != null) {
         return content;
       }
     }
   }
   return null;
 }
예제 #7
0
  /*
   * (non-Javadoc)
   *
   * @see javax.servlet.http.HttpServlet#service(javax.servlet.ServletRequest,
   * javax.servlet.ServletResponse)
   */
  @Override
  public void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    try {
      String messageId = request.getParameter("messageId");
      String attachmentIndex = request.getParameter("attachmentIndex");
      boolean isThumbnail = Boolean.valueOf(request.getParameter("thumbnail")).booleanValue();

      if (messageId != null) {
        IMailbox mailbox = SessionManager.get().getMailbox();
        Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId));

        if (isThumbnail) {
          List<MimePart> attachmentList = MessageUtils.attachmentsFromPart(msg);
          int index = Integer.valueOf(attachmentIndex);

          MimePart retrievePart = attachmentList.get(index);

          ContentType contentType = new ContentType(retrievePart.getContentType());
          response.setContentType(contentType.getBaseType());

          BufferedInputStream bufInputStream =
              new BufferedInputStream(retrievePart.getInputStream());
          OutputStream outputStream = response.getOutputStream();

          writeScaledImage(bufInputStream, outputStream);

          bufInputStream.close();
          outputStream.flush();
          outputStream.close();
        } else {
          Part imagePart = findImagePart(msg);
          if (imagePart != null) {
            ContentType contentType = new ContentType(imagePart.getContentType());
            response.setContentType(contentType.getBaseType());

            BufferedInputStream bufInputStream =
                new BufferedInputStream(imagePart.getInputStream());
            OutputStream outputStream = response.getOutputStream();

            byte[] inBuf = new byte[1024];
            int len = 0;
            int total = 0;
            while ((len = bufInputStream.read(inBuf)) > 0) {
              outputStream.write(inBuf, 0, len);
              total += len;
            }

            bufInputStream.close();
            outputStream.flush();
            outputStream.close();
          }
        }
      }
    } catch (Exception ex) {
      log.error(ex.getMessage(), ex);
    }
  }
  public FileContentInfo create(FileContent fileContent) throws FileSystemException {
    MimeFileObject mimeFile = (MimeFileObject) fileContent.getFile();
    Part part = mimeFile.getPart();

    String contentTypeString = null;
    String charset = null;

    try {
      // special handling for multipart
      if (mimeFile.isMultipart()) {
        // get the original content type, but ...
        contentTypeString = part.getContentType();

        // .... we deliver the preamble instead of an inupt string
        // the preamble will be delivered in UTF-8 - fixed
        charset = MimeFileSystem.PREAMBLE_CHARSET;
      }
    } catch (MessagingException e) {
      throw new FileSystemException(e);
    }

    if (contentTypeString == null) {
      // normal message ... get the content type
      try {
        contentTypeString = part.getContentType();
      } catch (MessagingException e) {
        throw new FileSystemException(e);
      }
    }

    ContentType contentType;
    try {
      contentType = new ContentType(contentTypeString);
    } catch (MessagingException e) {
      throw new FileSystemException(e);
    }

    if (charset == null) {
      // charset might already be set by the multipart message stuff, else
      // extract it from the contentType now
      charset = contentType.getParameter("charset"); // NON-NLS
    }

    return new DefaultFileContentInfo(contentType.getBaseType(), charset);
  }
  private void extractPart(final Part part) throws MessagingException, IOException {
    if (part.getContent() instanceof Multipart) {
      Multipart mp = (Multipart) part.getContent();
      for (int i = 0; i < mp.getCount(); i++) {
        extractPart(mp.getBodyPart(i));
      }
      return;
    }

    if (part.getContentType().startsWith("text/html")) {
      if (bodytext == null) {
        bodytext = (String) part.getContent();
      } else {
        bodytext = bodytext + "<HR/>" + (String) part.getContent();
      }
    } else if (!part.getContentType().startsWith("text/plain")) {
      Attachment attachment = new Attachment();
      attachment.setContenttype(part.getContentType());
      attachment.setFilename(part.getFileName());

      InputStream in = part.getInputStream();
      ByteArrayOutputStream bos = new ByteArrayOutputStream();

      byte[] buffer = new byte[8192];
      int count = 0;
      while ((count = in.read(buffer)) >= 0) bos.write(buffer, 0, count);
      in.close();
      attachment.setContent(bos.toByteArray());
      attachments.add(attachment);
    }

    if (!StringUtils.isNull(bodytext) && bodytext.indexOf("Original Message") > -1) {
      subBody = bodytext.substring(0, bodytext.indexOf("Original Message"));
    } else if (!StringUtils.isNull(bodytext)
        && bodytext.indexOf(", \"[email protected]\" <*****@*****.**> wrote:") > -1) {
      String tempstr =
          bodytext.substring(
              0, bodytext.indexOf(", \"[email protected]\" <*****@*****.**> wrote:"));
      subBody = tempstr.substring(0, tempstr.lastIndexOf("On"));
    }
  }
  /** Return the primary text content of the message. */
  private static String getText(Part p) throws MessagingException, IOException {

    if (p.isMimeType("text/enriched")) {
      InputStream is = (InputStream) p.getContent();
      StringWriter writer = new StringWriter();
      IOUtils.copy(is, writer);
      return writer.toString();
    }

    if (p.isMimeType("text/*") && !p.isMimeType("text/enriched")) {
      p.getContentType();

      try {
        String s = (String) p.getContent();
        textIsHtml = p.isMimeType("text/html");
        return s;
      } catch (ClassCastException e) {
        InputStream is = (InputStream) p.getContent();
        StringWriter writer = new StringWriter();
        IOUtils.copy(is, writer);
        textIsHtml = p.isMimeType("text/html");
        return writer.toString();
      }
    }

    if (p.isMimeType("multipart/alternative")) {
      // prefer html text over plain text
      Multipart mp = (Multipart) p.getContent();
      String text = null;
      for (int i = 0; i < mp.getCount(); i++) {
        Part bp = mp.getBodyPart(i);
        if (bp.isMimeType("text/plain")) {
          if (text == null) text = getText(bp);
          return text;
          // continue;
        } else if (bp.isMimeType("text/html")) {
          String s = getText(bp);
          if (s != null) return s;
        } else {
          return getText(bp);
        }
      }
      return text;
    } else if (p.isMimeType("multipart/*")) {
      Multipart mp = (Multipart) p.getContent();
      for (int i = 0; i < mp.getCount(); i++) {
        String s = getText(mp.getBodyPart(i));
        if (s != null) return s;
      }
    }

    return null;
  }
예제 #11
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);
        }
      }
    }
  }
예제 #12
0
 public static InputStream getAttachment(Part part, String filename) {
   try {
     if (filename.equals(part.getFileName())) return part.getInputStream();
     if (part.getContentType().toLowerCase().startsWith("multipart")) {
       MimeMultipart multipart;
       multipart = (MimeMultipart) part.getContent();
       int count = multipart.getCount();
       for (int i = 0; i < count; i++) {
         InputStream in = getAttachment(multipart.getBodyPart(i), filename);
         if (in != null) return in;
       }
     }
   } catch (Throwable ex) {
     throw new RuntimeException(ex);
   }
   return null;
 }
예제 #13
0
  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());
  }
예제 #14
0
  // x参数来确定是以html 1 格式显示还是以plain 2
  // 调用时getPart(part,i,1);
  // 显示复杂邮件的正文内容
  public String getPart(Part part, int partNum, int x) throws MessagingException, IOException {

    String s = "";
    String s1 = "";
    String s2 = "";
    String s5 = "";
    String sct = part.getContentType();
    if (sct == null) {
      s = "part 无效";
      return s;
    }
    ContentType ct = new ContentType(sct);
    if (ct.match("text/html") || ct.match("text/plain")) {
      // display text/plain inline
      s1 = "" + (String) part.getContent() + "";
    } else if (partNum != 0) {
      String temp = "";
      if ((temp = part.getFileName()) != null) {
        s2 = "Filename: " + temp + "";
      }
    }
    if (part.isMimeType("multipart/alternative")) {
      String s6 = "";
      String s7 = "";
      Multipart mp = (Multipart) part.getContent();
      int count = mp.getCount();
      for (int i = 0; i < count; i++) {
        if (mp.getBodyPart(i).isMimeType("text/plain")) s7 = getPart(mp.getBodyPart(i), i, 2);
        else if (mp.getBodyPart(i).isMimeType("text/html")) s6 = getPart(mp.getBodyPart(i), i, 1);
      }
      if (x == 1) { // html格式的字符串
        s5 = s6;
      }
      if (x == 2) { // paint类型的字符串
        s5 = s7;
      }
      return s5;
    }
    s = s1 + s2;
    return s;
  }
예제 #15
0
 public static Set<String> getAttachmentFilenames(Part part) {
   try {
     Set<String> result = new HashSet<String>();
     if (part.getContentType().toLowerCase().startsWith("multipart")) {
       MimeMultipart multipart;
       try {
         multipart = (MimeMultipart) part.getContent();
         int count = multipart.getCount();
         for (int i = 0; i < count; i++) {
           result.addAll(getAttachmentFilenames(multipart.getBodyPart(i)));
         }
       } catch (NullPointerException ex) {
         // part.getContent() throws NullPointerException
         LOG.info(ex);
       }
     } else {
       String filename = part.getFileName();
       if (filename != null) result.add(Str.decodeQuotedPrintable(filename));
     }
     return result;
   } catch (Exception ex) {
     throw new RuntimeException(ex);
   }
 }
  /*
   * 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());
      }
    }
  }
예제 #17
0
  /**
   * 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);
    }
  }
예제 #18
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 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("---------------------------");
      }
    }
  }
예제 #20
0
 public static String getTextContent(Part part, String type) {
   if (part == null) return null;
   try {
     String contentType;
     try {
       contentType = part.getContentType();
     } catch (Throwable t) {
       contentType = "unknown";
     }
     if (contentType.toLowerCase().startsWith("text/" + type)) {
       // ContentType ct = new ContentType(contentType);
       // String charset = ct.getParameter("charset");
       try {
         Object content = part.getContent();
         if (content == null) return null;
         if (content instanceof String) return (String) content;
         if (content instanceof InputStream) {
           String encoding = charset;
           if (contentType.toLowerCase().contains("UTF")) encoding = IO.UTF_8;
           if (contentType.toLowerCase().contains("ISO")) encoding = IO.ISO_LATIN_1;
           return IO.readToString((InputStream) content, encoding);
         }
         return Utl.toStringWithType(content);
       } catch (UnsupportedEncodingException ex) {
         LOG.warn(ex);
         return null;
       } catch (IOException e) {
         String message = e.getMessage();
         if (message != null) {
           if ("No content".equals(message)) {
             return null;
           }
           if (message.toLowerCase().startsWith("unknown encoding")) {
             LOG.warn(e);
             return null;
           }
         }
         throw e;
       } catch (Throwable t) {
         LOG.warn(t);
         return Str.getStackTrace(t);
       }
     }
     if (contentType.toLowerCase().startsWith("multipart")) {
       MimeMultipart multipart;
       try {
         multipart = (MimeMultipart) part.getContent();
       } catch (NullPointerException ex) {
         LOG.warn(ex);
         return null;
       }
       int count = multipart.getCount();
       for (int i = 0; i < count; i++) {
         BodyPart subPart = multipart.getBodyPart(i);
         String filename = subPart.getFileName();
         if (filename != null) continue;
         String text = getTextContent(subPart, type);
         if (text != null) return text.trim();
       }
       return null;
     }
     return null;
   } catch (Exception ex) {
     throw new RuntimeException(ex);
   }
 }
  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");
  }