/** Return the primary text content of the message. */
  public String getContent(Part p) throws MessagingException, IOException {
    if (p.isMimeType("text/*")) {
      String s = (String) p.getContent();
      return s;
    }

    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 = getContent(bp);
          continue;
        } else if (bp.isMimeType("text/html")) {
          String s = getContent(bp);
          if (s != null) return s;
        } else {
          return getContent(bp);
        }
      }
      return text;
    } else if (p.isMimeType("multipart/*")) {
      Multipart mp = (Multipart) p.getContent();
      for (int i = 0; i < mp.getCount(); i++) {
        String s = getContent(mp.getBodyPart(i));
        if (s != null) return s;
      }
    }

    return null;
  }
  /** 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;
  }
  /**
   * 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();
  }
  public void setMessage(MimeMessage message) {
    if (message != null) {
      // serialize the message
      this.message = message;
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      try {
        message.writeTo(baos);
        baos.flush();
        serializedBytes = baos.toByteArray();
        this.contentType = message.getContentType();

        // see if this is a multi-part message
        Object content = message.getContent();
        if (content instanceof Multipart) {
          Multipart mp = (Multipart) content;
          this.parts = mp.getCount();
        } else {
          this.parts = 0;
        }
      } catch (MessagingException e) {
        Debug.logError(e, module);
      } catch (IOException e) {
        Debug.logError(e, module);
      } finally {
        try {
          baos.close();
        } catch (IOException e) {
          Debug.logError(e, module);
        }
      }
    }
  }
Example #5
0
  /**
   * 对复杂邮件的解析
   *
   * @param multipart
   * @throws MessagingException
   * @throws IOException
   */
  public static void parseMultipart(Multipart multipart) throws MessagingException, IOException {
    int count = multipart.getCount();
    System.out.println("couont =  " + count);
    for (int idx = 0; idx < count; idx++) {
      BodyPart bodyPart = multipart.getBodyPart(idx);
      System.out.println(bodyPart.getContentType());
      if (bodyPart.isMimeType("text/plain")) {
        System.out.println("plain................." + bodyPart.getContent());
      } else if (bodyPart.isMimeType("text/html")) {
        System.out.println("html..................." + bodyPart.getContent());
      } else if (bodyPart.isMimeType("multipart/*")) {
        Multipart mpart = (Multipart) bodyPart.getContent();
        parseMultipart(mpart);

      } else if (bodyPart.isMimeType("application/octet-stream")) {
        String disposition = bodyPart.getDisposition();
        System.out.println(disposition);
        if (disposition.equalsIgnoreCase(BodyPart.ATTACHMENT)) {
          String fileName = bodyPart.getFileName();
          InputStream is = bodyPart.getInputStream();
          copy(is, new FileOutputStream("D:\\" + fileName));
        }
      }
    }
  }
Example #6
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);
    }
  }
Example #7
0
  /**
   * Extracts the content of a MimeMessage recursively.
   *
   * @param parent the parent multi-part
   * @param part the current MimePart
   * @throws MessagingException parsing the MimeMessage failed
   * @throws IOException parsing the MimeMessage failed
   */
  protected void parse(final Multipart parent, final MimePart part)
      throws MessagingException, IOException {
    if (isMimeType(part, "text/plain")
        && plainContent == null
        && !MimePart.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
      plainContent = (String) part.getContent();
    } else {
      if (isMimeType(part, "text/html")
          && htmlContent == null
          && !MimePart.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
        htmlContent = (String) part.getContent();
      } else {
        if (isMimeType(part, "multipart/*")) {
          this.isMultiPart = true;
          final Multipart mp = (Multipart) part.getContent();
          final int count = mp.getCount();

          // iterate over all MimeBodyPart

          for (int i = 0; i < count; i++) {
            parse(mp, (MimeBodyPart) mp.getBodyPart(i));
          }
        } else {
          final String cid = stripContentId(part.getContentID());
          final DataSource ds = createDataSource(parent, part);
          if (cid != null) {
            this.cidMap.put(cid, ds);
          }
          this.attachmentList.add(ds);
        }
      }
    }
  }
 /**
  * Determine whether the attachment's quantity exceeds the max attachment count or not.
  *
  * @param multi
  * @return
  * @throws MessagingException
  */
 protected int countMailAttachments(Multipart multi) throws MessagingException {
   int mailAttachments = 0;
   // Normally, only 1 BodyPart is email text, others are attachments.
   // So the whole BodyPart minus 1 is the attachment quantity.
   int attachmentCount = multi.getCount();
   mailAttachments = attachmentCount - 1;
   return mailAttachments;
 }
 private void loadMail(Part p) throws Exception {
   Object content = p.getContent();
   if (content instanceof Multipart) {
     Multipart mp = (Multipart) content;
     int cnt = mp.getCount();
     for (int i = 0; i < cnt; i++) loadMail(mp.getBodyPart(i));
   }
 }
    private String getRawText(Object o) throws MessagingException, IOException {

      String s = null;

      if (o instanceof Multipart) {
        Multipart multi = (Multipart) o;
        for (int i = 0; i < multi.getCount(); i++) {
          s = getRawText(multi.getBodyPart(i));
          if (s != null) {
            if (s.length() > 0) {
              break;
            }
          }
        }
      } else if (o instanceof BodyPart) {
        BodyPart aBodyContent = (BodyPart) o;
        StringTokenizer aTypeTokenizer = new StringTokenizer(aBodyContent.getContentType(), "/");
        String abstractType = aTypeTokenizer.nextToken();
        if (abstractType.compareToIgnoreCase("MESSAGE") == 0) {
          Message inlineMessage = (Message) aBodyContent.getContent();
          s = getRawText(inlineMessage.getContent());
        }
        if (abstractType.compareToIgnoreCase("APPLICATION") == 0) {
          s = "Attached File: " + aBodyContent.getFileName();
        }
        if (abstractType.compareToIgnoreCase("TEXT") == 0) {
          try {
            Object oS = aBodyContent.getContent();
            if (oS instanceof String) {
              s = (String) oS;
            } else {
              throw (new MessagingException("Unkown MIME Type (?): " + oS.getClass()));
            }
          } catch (Exception e) {
            throw (new MessagingException(
                "Unable to read message contents (" + e.getMessage() + ")"));
          }
        }
        if (abstractType.compareToIgnoreCase("MULTIPART") == 0) {
          s = getRawText(aBodyContent.getContent());
        }
      }

      if (o instanceof String) {
        s = (String) o;
      }

      //          else {
      //              if (m.isMimeType("text/html")) {
      //                  s = m.getContent().toString();
      //              }
      //              if (m.isMimeType("text/plain")) {
      //                  s = m.getContent().toString();
      //              }
      //          }

      return s;
    }
  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());
  }
  /** Method for checking if the message has attachments. */
  public boolean hasAttachments() throws java.io.IOException, MessagingException {
    boolean hasAttachments = false;
    if (message.isMimeType("multipart/*")) {
      Multipart mp = (Multipart) message.getContent();
      if (mp.getCount() > 1) hasAttachments = true;
    }

    return hasAttachments;
  }
Example #13
0
 private void extractFiles() throws IOException, MessagingException {
   if (message.getContent() instanceof Multipart) {
     Multipart mp = (Multipart) message.getContent();
     for (int i = 0; i < mp.getCount(); i++) {
       BodyPart bp = mp.getBodyPart(i);
       getMultipart(bp, bp.getContent());
     }
   }
 }
    /**
     * Handel multipart messages recursive until we find the first text/html message. Or text/plain
     * if html is not available.
     *
     * @param multipart the multipart portion
     * @param message the message
     * @param builder the email value builder
     * @throws MessagingException
     * @throws IOException
     */
    private void handleMultipart(
        Multipart multipart, Message message, ValueBuilder<EmailValue> builder)
        throws MessagingException, IOException {
      String body = "";

      String contentType = cleanContentType(multipart.getContentType());

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

        String disposition = part.getDisposition();

        if ((disposition != null)
            && ((disposition.equalsIgnoreCase(Part.ATTACHMENT)
                || (disposition.equalsIgnoreCase(Part.INLINE))))) {
          builder
              .prototype()
              .attachments()
              .get()
              .add(createAttachedFileValue(message.getSentDate(), part));

        } else {
          if (part.isMimeType(Translator.PLAIN)) {
            // if contents is multipart mixed concatenate text plain parts
            if ("multipart/mixed".equalsIgnoreCase(contentType)) {
              body += (String) part.getContent() + "\n\r";
            } else {
              body = (String) part.getContent();
            }
            builder.prototype().content().set(body);
            builder.prototype().contentType().set(Translator.PLAIN);

          } else if (part.isMimeType(Translator.HTML)) {
            body = (String) part.getContent();
            builder.prototype().contentHtml().set(body);
            builder.prototype().contentType().set(Translator.HTML);

          } else if (part.isMimeType("image/*")) {
            builder
                .prototype()
                .attachments()
                .get()
                .add(createAttachedFileValue(message.getSentDate(), part));

          } else if (part.getContent() instanceof Multipart) {
            handleMultipart((Multipart) part.getContent(), message, builder);
          }
        }
      }
      // if contentHtml is not empty set the content type to text/html
      if (!Strings.empty(builder.prototype().contentHtml().get())) {
        builder.prototype().content().set(builder.prototype().contentHtml().get());
        builder.prototype().contentType().set(Translator.HTML);
      }
    }
  /**
   * 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();
  }
 private void findParts(List<BodyPart> list, Multipart multipart)
     throws MessagingException, IOException {
   for (int ii = 0; ii < multipart.getCount(); ii++) {
     BodyPart bodyPart = multipart.getBodyPart(ii);
     list.add(bodyPart);
     Object content = bodyPart.getContent();
     if (content instanceof Multipart) {
       Multipart mp = (Multipart) content;
       findParts(list, mp);
     }
   }
 }
Example #17
0
 /**
  * 分析邮件
  *
  * @param content
  */
 public static void parseMailContent(Object content) {
   try {
     if (content instanceof Multipart) {
       Multipart mPart = (MimeMultipart) content;
       for (int i = 0; i < mPart.getCount(); i++) {
         extractPart((MimeBodyPart) mPart.getBodyPart(i));
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Example #18
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;
 }
Example #19
0
 public static Part getTextFromMultipart(Part p) throws MessagingException, IOException {
   Part text = null;
   if (p.isMimeType("multipart/*")) {
     System.out.println("rec");
     Multipart mp = (Multipart) p.getContent();
     int count = mp.getCount();
     for (int i = 0; i < count; ) return getTextFromMultipart(mp.getBodyPart(i));
   } else if (p.isMimeType("text/plain")) {
     System.out.println("text");
     text = p;
   }
   return text;
 }
Example #20
0
  // 取得邮件列表的信息
  @SuppressWarnings({"rawtypes", "unchecked"})
  public List getMailInfo(Message[] msg) throws Exception {
    List result = new ArrayList();
    Map map = null;
    Multipart mp = null;
    BodyPart part = null;
    String disp = null;
    SimpleDateFormat fmt = new SimpleDateFormat("yyyy年MM月dd日 hh:mm-ss");
    Enumeration enumMail = null;
    // 取出每个邮件的信息
    for (int i = msg.length - 1; i >= 0; i--) {
      if (!msg[i].getFolder().isOpen()) // 判断是否open
      msg[i].getFolder().open(Folder.READ_WRITE);
      map = new HashMap();
      // 读取邮件ID
      enumMail = msg[i].getAllHeaders();
      Header h = null;
      while (enumMail.hasMoreElements()) {
        h = (Header) enumMail.nextElement();
        if (h.getName().equals("Message-ID") || h.getName().equals("Message-Id")) {
          map.put("ID", h.getValue());
        }
      }
      // 读取邮件标题
      map.put("subject", msg[i].getSubject());
      // 读取发件人
      map.put("sender", MimeUtility.decodeText(msg[i].getFrom()[0].toString()));
      // 读取邮件发送日期
      map.put("senddate", fmt.format(msg[i].getSentDate()));
      // 读取邮件大小
      map.put("size", new Integer(msg[i].getSize()));
      map.put("hasAttach", "&nbsp;");
      // 判断是否有附件
      if (msg[i].isMimeType("multipart/*")) {
        mp = (Multipart) msg[i].getContent();
        // 遍历每个Miltipart对象

        for (int j = 0; j < mp.getCount(); j++) {
          part = mp.getBodyPart(j);
          disp = part.getDisposition();
          // 如果有附件
          if (disp != null && (disp.equals(Part.ATTACHMENT) || disp.equals(Part.INLINE))) {
            // 设置有附件的特征值
            map.put("hasAttach", "√");
          }
        }
      }
      result.add(map);
    }
    return result;
  }
 public void saveEmailFiles(HttpServletRequest request, HttpServletResponse response, Part part)
     throws Exception {
   String fileName = "";
   if (part.isMimeType("multipart/*")) {
     Multipart mp = (Multipart) part.getContent();
     for (int i = 0; i < mp.getCount(); i++) {
       BodyPart mpart = mp.getBodyPart(i);
       String disposition = mpart.getDisposition();
       if ((disposition != null)
           && ((disposition.equals(Part.ATTACHMENT)) || (disposition.equals(Part.INLINE)))) {
         fileName = mpart.getFileName();
         if (fileName != null) {
           if (fileName.toLowerCase().indexOf("gb2312") != -1
               || fileName.toLowerCase().indexOf("gbk") != -1) {
             fileName = MimeUtility.decodeText(fileName);
           }
           if (request.getHeader("User-Agent").contains("Firefox")) {
             response.addHeader("content-disposition", "attachment;filename=" + fileName);
           } else if (request.getHeader("User-Agent").contains("MSIE")) {
             response.addHeader(
                 "content-disposition",
                 "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
           }
           System.out.println("saveFile1");
           saveFile(response, fileName, mpart.getInputStream());
         }
       } else if (mpart.isMimeType("multipart/*")) {
         saveEmailFiles(request, response, mpart);
       } else {
         fileName = mpart.getFileName();
         if (fileName != null) {
           if (fileName.toLowerCase().indexOf("gb2312") != -1
               || fileName.toLowerCase().indexOf("gbk") != -1) {
             fileName = MimeUtility.decodeText(fileName);
           }
           if (request.getHeader("User-Agent").contains("Firefox")) {
             response.addHeader("content-disposition", "attachment;filename=" + fileName);
           } else if (request.getHeader("User-Agent").contains("MSIE")) {
             response.addHeader(
                 "content-disposition",
                 "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
           }
           System.out.println("saveFile2");
           saveFile(response, fileName, mpart.getInputStream());
         }
       }
     }
   } else if (part.isMimeType("message/rfc822")) {
     saveEmailFiles(request, response, (Part) part.getContent());
   }
 }
Example #22
0
  private void getMultipart(BodyPart bp, Object content) throws IOException, MessagingException {
    if (!(content instanceof Multipart)) {
      if (bp.getFileName() != null && content instanceof InputStream) {
        files.put(bp.getFileName(), (InputStream) content);
      }
      return;
    }

    Multipart mp = (Multipart) content;
    for (int i = 0; i < mp.getCount(); i++) {
      BodyPart newBp = mp.getBodyPart(i);
      getMultipart(newBp, newBp.getContent());
    }
  }
Example #23
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();
    }
  }
  /**
   * Count the mail attachments' size, it is a total mail attachments' size.
   *
   * @param multi
   * @param mailAttachmentsSize
   * @return
   * @throws MessagingException
   * @throws IOException
   */
  protected int countMailAttachmentsSize(Multipart multi, int mailAttachmentsSize)
      throws MessagingException, IOException {
    for (int i = 0, n = multi.getCount(); i < n; i++) {
      Part part = multi.getBodyPart(i);

      if (part.getContent() instanceof Multipart) {
        mailAttachmentsSize =
            this.countMailAttachmentsSize((Multipart) part.getContent(), mailAttachmentsSize);
      }
      int partSize = part.getSize();
      if (partSize != -1) {
        mailAttachmentsSize = mailAttachmentsSize + partSize;
      }
    }
    return mailAttachmentsSize;
  }
Example #25
0
 /**
  * @param multipart // 接卸包裹(含所有邮件内容(包裹+正文+附件))
  * @throws Exception
  */
 private void reMultipart(Multipart multipart) throws Exception {
   // System.out.println("邮件共有" + multipart.getCount() + "部分组成");
   // 依次处理各个部分
   for (int j = 0, n = multipart.getCount(); j < n; j++) {
     // System.out.println("处理第" + j + "部分");
     Part part = multipart.getBodyPart(j); // 解包, 取出 MultiPart的各个部分, 每部分可能是邮件内容,
     // 也可能是另一个小包裹(MultipPart)
     // 判断此包裹内容是不是一个小包裹, 一般这一部分是 正文 Content-Type: multipart/alternative
     if (part.getContent() instanceof Multipart) {
       Multipart p = (Multipart) part.getContent(); // 转成小包裹
       // 递归迭代
       reMultipart(p);
     } else {
       rePart(part);
     }
   }
 }
 /**
  * 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;
 }
Example #27
0
  private String getText(Object content) throws IOException, MessagingException {
    String text = null;
    StringBuffer sb = new StringBuffer();

    if (content instanceof String) {
      sb.append((String) content);
    } else if (content instanceof Multipart) {
      Multipart mp = (Multipart) content;
      for (int i = 0; i < mp.getCount(); i++) {
        BodyPart bp = mp.getBodyPart(i);
        sb.append(getText(bp.getContent()));
      }
    }

    text = sb.toString();
    return text;
  }
  /**
   * Either every recipient is matching or neither of them.
   *
   * @throws MessagingException if no attachment is found and at least one exception was thrown
   */
  public Collection match(Mail mail) throws MessagingException {

    Exception anException = null;

    try {
      MimeMessage message = mail.getMessage();
      Object content;

      /** if there is an attachment and no inline text, the content type can be anything */
      if (message.getContentType() == null) {
        return null;
      }

      content = message.getContent();
      if (content instanceof Multipart) {
        Multipart multipart = (Multipart) content;
        for (int i = 0; i < multipart.getCount(); i++) {
          try {
            Part part = multipart.getBodyPart(i);
            String fileName = part.getFileName();
            if (fileName != null) {
              return mail.getRecipients(); // file found
            }
          } catch (MessagingException e) {
            anException = e;
          } // ignore any messaging exception and process next bodypart
        }
      } else {
        String fileName = message.getFileName();
        if (fileName != null) {
          return mail.getRecipients(); // file found
        }
      }
    } catch (Exception e) {
      anException = e;
    }

    // if no attachment was found and at least one exception was catched rethrow it up
    if (anException != null) {
      throw new MessagingException("Malformed message", anException);
    }

    return null; // no attachment found
  }
 /** 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 #30
0
 // 读取邮件内容
 @SuppressWarnings({"rawtypes", "unchecked"})
 public Map readMail(String id) throws Exception {
   Map map = new HashMap();
   // 找到目标邮件
   Message readmsg = findMail(msg, id);
   // 读取邮件标题
   map.put("subject", readmsg.getSubject());
   // 读取发件人
   map.put("sender", MimeUtility.decodeText(readmsg.getFrom()[0].toString()));
   map.put("attach", "");
   // 取得邮件内容
   if (readmsg.isMimeType("text/*")) {
     map.put("content", readmsg.getContent().toString());
   } else {
     System.out.println("this is not a text mail");
     Multipart mp = (Multipart) readmsg.getContent();
     if (mp == null) {
       System.out.println("the content is null");
     } else System.out.println("--------------------------multipart:" + mp.toString());
     BodyPart part = null;
     String disp = null;
     StringBuffer result = new StringBuffer();
     // 遍历每个Miltipart对象
     for (int j = 0; j < mp.getCount(); j++) {
       part = mp.getBodyPart(j);
       disp = part.getDisposition();
       // 如果有附件
       if (disp != null && (disp.equals(Part.ATTACHMENT) || disp.equals(Part.INLINE))) {
         // 取得附件文件名
         String filename = MimeUtility.decodeText(part.getFileName()); // 解决中文附件名的问题
         map.put("attach", filename);
         // 下载附件
         InputStream in = part.getInputStream(); // 附件输入流
         if (attachFile.isDownload(filename)) attachFile.choicePath(filename, in); // // 下载附件
       } else {
         // 显示复杂邮件正文内容
         result.append(getPart(part, j, 1));
       }
     }
     map.put("content", result.toString());
   }
   return map;
 }