Пример #1
0
  /**
   * Gets the message type based on the content type headers.
   *
   * @param msg The message to extract the type from.
   * @return MDN if the message is an MDN message (<a href="http://tools.ietf.org/html/rfc3798">RFC
   *     3798</a>)<br>
   *     DSN if the message is a DNS message (<a href="http://tools.ietf.org/html/rfc3464">RFC
   *     3464</a>)<br>
   *     Normal for all other message type.<br>
   *     Return Unknown if an error occurs.
   */
  public static TxMessageType getMessageType(MimeMessage msg) {
    try {
      ContentType contentType = new ContentType(msg.getContentType());

      if (contentType.match(MDNStandard.MediaType.ReportMessage)
          && contentType.getParameter(MDNStandard.MediaType.ReportType) != null) {

        if (contentType
            .getParameter(MDNStandard.MediaType.ReportType)
            .equalsIgnoreCase(MDNStandard.MediaType.ReportTypeValueNotification))
          return TxMessageType.MDN;
        else if (contentType
            .getParameter(DSNStandard.MediaType.ReportType)
            .equalsIgnoreCase(DSNStandard.MediaType.ReportTypeValueDelivery))
          return TxMessageType.DSN;
      } else if (contentType.match(SMIMEStandard.EncryptedContentMediaType)
          || contentType.match(SMIMEStandard.EncryptedContentMediaTypeAlternative)) {
        return TxMessageType.SMIME;
      }

      return TxMessageType.IMF;
    }
    /// CLOVER:OFF
    catch (ParseException e) {
      LOGGER.warn("Failed to discern message type.", e);
    } catch (MessagingException e) {
      LOGGER.warn("Failed to discern message type.", e);
    }
    return TxMessageType.UNKNOWN;
    /// CLOVER:ON
  }
Пример #2
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;
  }
Пример #3
0
  /**
   * Checks whether the MimePart contains an object of the given mime type.
   *
   * @param part the current MimePart
   * @param mimeType the mime type to check
   * @return {@code true} if the MimePart matches the given mime type, {@code false} otherwise
   * @throws MessagingException parsing the MimeMessage failed
   * @throws IOException parsing the MimeMessage failed
   */
  private boolean isMimeType(final MimePart part, final String mimeType)
      throws MessagingException, IOException {
    // Do not use part.isMimeType(String) as it is broken for MimeBodyPart
    // and does not really check the actual content type.

    try {
      final ContentType ct = new ContentType(part.getDataHandler().getContentType());
      return ct.match(mimeType);
    } catch (final ParseException ex) {
      return part.getContentType().equalsIgnoreCase(mimeType);
    }
  }
 private void writeBodyPart(byte[] bodyContent, Part part, ContentType contentType)
     throws MessagingException {
   DataSource ds = new ByteArrayDataSource(bodyContent, contentType.toString());
   part.setDataHandler(new DataHandler(ds));
   part.setHeader(CONTENT_TYPE, contentType.toString());
   if (contentType.match("text/*")) {
     part.setHeader(CONTENT_TRANSFER_ENCODING, "8bit");
   } else if (binaryContent) {
     part.setHeader(CONTENT_TRANSFER_ENCODING, "binary");
   } else {
     part.setHeader(CONTENT_TRANSFER_ENCODING, "base64");
   }
 }
 private ContentType getContentType(Exchange exchange) throws ParseException {
   String contentTypeStr = ExchangeHelper.getContentType(exchange);
   if (contentTypeStr == null) {
     contentTypeStr = DEFAULT_CONTENT_TYPE;
   }
   ContentType contentType = new ContentType(contentTypeStr);
   String contentEncoding = ExchangeHelper.getContentEncoding(exchange);
   // add a charset parameter for text subtypes
   if (contentEncoding != null && contentType.match("text/*")) {
     contentType.setParameter("charset", MimeUtility.mimeCharset(contentEncoding));
   }
   return contentType;
 }
 @Override
 public void marshal(Exchange exchange, Object graph, OutputStream stream)
     throws NoTypeConversionAvailableException, MessagingException, IOException {
   if (multipartWithoutAttachment || headersInline || exchange.getIn().hasAttachments()) {
     ContentType contentType = getContentType(exchange);
     // remove the Content-Type header. This will be wrong afterwards...
     exchange.getOut().removeHeader(Exchange.CONTENT_TYPE);
     byte[] bodyContent = ExchangeHelper.convertToMandatoryType(exchange, byte[].class, graph);
     Session session = Session.getInstance(System.getProperties());
     MimeMessage mm = new MimeMessage(session);
     MimeMultipart mp = new MimeMultipart(multipartSubType);
     BodyPart part = new MimeBodyPart();
     writeBodyPart(bodyContent, part, contentType);
     mp.addBodyPart(part);
     for (Map.Entry<String, Attachment> entry :
         exchange.getIn().getAttachmentObjects().entrySet()) {
       String attachmentFilename = entry.getKey();
       Attachment attachment = entry.getValue();
       part = new MimeBodyPart();
       part.setDataHandler(attachment.getDataHandler());
       part.setFileName(MimeUtility.encodeText(attachmentFilename, "UTF-8", null));
       String ct = attachment.getDataHandler().getContentType();
       contentType = new ContentType(ct);
       part.setHeader(CONTENT_TYPE, ct);
       if (!contentType.match("text/*") && binaryContent) {
         part.setHeader(CONTENT_TRANSFER_ENCODING, "binary");
       }
       // Set headers to the attachment
       for (String headerName : attachment.getHeaderNames()) {
         List<String> values = attachment.getHeaderAsList(headerName);
         for (String value : values) {
           part.setHeader(headerName, value);
         }
       }
       mp.addBodyPart(part);
       exchange.getOut().removeAttachment(attachmentFilename);
     }
     mm.setContent(mp);
     // copy headers if required and if the content can be converted into
     // a String
     if (headersInline && includeHeaders != null) {
       for (Map.Entry<String, Object> entry : exchange.getIn().getHeaders().entrySet()) {
         if (includeHeaders.matcher(entry.getKey()).matches()) {
           String headerStr =
               ExchangeHelper.convertToType(exchange, String.class, entry.getValue());
           if (headerStr != null) {
             mm.setHeader(entry.getKey(), headerStr);
           }
         }
       }
     }
     mm.saveChanges();
     Enumeration<?> hl = mm.getAllHeaders();
     List<String> headers = new ArrayList<String>();
     if (!headersInline) {
       while (hl.hasMoreElements()) {
         Object ho = hl.nextElement();
         if (ho instanceof Header) {
           Header h = (Header) ho;
           exchange.getOut().setHeader(h.getName(), h.getValue());
           headers.add(h.getName());
         }
       }
       mm.saveChanges();
     }
     mm.writeTo(stream, headers.toArray(new String[0]));
   } else {
     // keep the original data
     InputStream is = ExchangeHelper.convertToMandatoryType(exchange, InputStream.class, graph);
     IOHelper.copyAndCloseInput(is, stream);
   }
 }
 @Override
 public Object unmarshal(Exchange exchange, InputStream stream)
     throws IOException, MessagingException {
   MimeBodyPart mimeMessage;
   String contentType;
   Message camelMessage;
   Object content = null;
   if (headersInline) {
     mimeMessage = new MimeBodyPart(stream);
     camelMessage = exchange.getOut();
     MessageHelper.copyHeaders(exchange.getIn(), camelMessage, true);
     contentType = mimeMessage.getHeader(CONTENT_TYPE, null);
     // write the MIME headers not generated by javamail as Camel headers
     Enumeration<?> headersEnum = mimeMessage.getNonMatchingHeaders(STANDARD_HEADERS);
     while (headersEnum.hasMoreElements()) {
       Object ho = headersEnum.nextElement();
       if (ho instanceof Header) {
         Header header = (Header) ho;
         camelMessage.setHeader(header.getName(), header.getValue());
       }
     }
   } else {
     // check if this a multipart at all. Otherwise do nothing
     contentType = exchange.getIn().getHeader(CONTENT_TYPE, String.class);
     if (contentType == null) {
       return stream;
     }
     try {
       ContentType ct = new ContentType(contentType);
       if (!ct.match("multipart/*")) {
         return stream;
       }
     } catch (ParseException e) {
       LOG.warn("Invalid Content-Type " + contentType + " ignored");
       return stream;
     }
     camelMessage = exchange.getOut();
     MessageHelper.copyHeaders(exchange.getIn(), camelMessage, true);
     ByteArrayOutputStream bos = new ByteArrayOutputStream();
     IOHelper.copyAndCloseInput(stream, bos);
     InternetHeaders headers = new InternetHeaders();
     extractHeader(CONTENT_TYPE, camelMessage, headers);
     extractHeader(MIME_VERSION, camelMessage, headers);
     mimeMessage = new MimeBodyPart(headers, bos.toByteArray());
     bos.close();
   }
   DataHandler dh;
   try {
     dh = mimeMessage.getDataHandler();
     if (dh != null) {
       content = dh.getContent();
       contentType = dh.getContentType();
     }
   } catch (MessagingException e) {
     LOG.warn("cannot parse message, no unmarshalling done");
   }
   if (content instanceof MimeMultipart) {
     MimeMultipart mp = (MimeMultipart) content;
     content = mp.getBodyPart(0);
     for (int i = 1; i < mp.getCount(); i++) {
       BodyPart bp = mp.getBodyPart(i);
       DefaultAttachment camelAttachment = new DefaultAttachment(bp.getDataHandler());
       @SuppressWarnings("unchecked")
       Enumeration<Header> headers = bp.getAllHeaders();
       while (headers.hasMoreElements()) {
         Header header = headers.nextElement();
         camelAttachment.addHeader(header.getName(), header.getValue());
       }
       camelMessage.addAttachmentObject(getAttachmentKey(bp), camelAttachment);
     }
   }
   if (content instanceof BodyPart) {
     BodyPart bp = (BodyPart) content;
     camelMessage.setBody(bp.getInputStream());
     contentType = bp.getContentType();
     if (contentType != null && !DEFAULT_CONTENT_TYPE.equals(contentType)) {
       camelMessage.setHeader(CONTENT_TYPE, contentType);
       ContentType ct = new ContentType(contentType);
       String charset = ct.getParameter("charset");
       if (charset != null) {
         camelMessage.setHeader(Exchange.CONTENT_ENCODING, MimeUtility.javaCharset(charset));
       }
     }
   } else {
     // If we find no body part, try to leave the message alone
     LOG.info("no MIME part found");
   }
   return camelMessage;
 }