Java Code Examples for javax.mail.Multipart#getCount()

The following examples show how to use javax.mail.Multipart#getCount() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MailUtil.java    From document-management-software with GNU Lesser General Public License v3.0 7 votes vote down vote up
private static void addAttachments(BodyPart p, EMail email, boolean extractAttachmentContent)
		throws UnsupportedEncodingException, MessagingException, IOException {
	if (p.isMimeType("multipart/*")) {
		Multipart mp = (Multipart) p.getContent();
		int count = mp.getCount();
		for (int i = 1; i < count; i++) {
			BodyPart bp = mp.getBodyPart(i);
			if (bp.getFileName() != null && extractAttachmentContent) {
				addAttachment(bp, email);
			} else if (bp.isMimeType("multipart/*")) {
				addAttachments(bp, email, extractAttachmentContent);
			}
		}
	} else if (extractAttachmentContent && StringUtils.isNotEmpty(p.getFileName())) {
		addAttachment(p, email);
	}
}
 
Example 2
Source File: MimeMessageWrapper.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
public synchronized void setMessage(MimeMessage message) {
    if (message != null) {
        // serialize the message
        this.message = message;
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            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 (IOException | MessagingException e) {
            Debug.logError(e, module);
        }
    }
}
 
Example 3
Source File: EmailReader.java    From baleen with Apache License 2.0 6 votes vote down vote up
private String getContent(Message msg) throws IOException, MessagingException {
  Object messageContentObject = msg.getContent();
  if (messageContentObject instanceof Multipart) {
    Multipart multipart = (Multipart) msg.getContent();

    // Loop over the parts of the email
    for (int i = 0; i < multipart.getCount(); i++) {
      // Retrieve the next part
      Part part = multipart.getBodyPart(i);

      if (!Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())
          && StringUtils.isBlank(part.getFileName())) {
        return part.getContent().toString();
      }
    }
  } else {
    return msg.getContent().toString().trim();
  }

  return "";
}
 
Example 4
Source File: MailReader.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * Get the content of a mail message.
 * 
 * @param message
 *            the mail message
 * @return the content of the mail message
 */
private String getMessageContent(Message message) throws MessagingException {
    try {
        Object content = message.getContent();
        if (content instanceof Multipart) {
            StringBuffer messageContent = new StringBuffer();
            Multipart multipart = (Multipart) content;
            for (int i = 0; i < multipart.getCount(); i++) {
                Part part = multipart.getBodyPart(i);
                if (part.isMimeType("text/plain")) {
                    messageContent.append(part.getContent().toString());
                }
            }
            return messageContent.toString();
        }
        return content.toString();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return "";
}
 
Example 5
Source File: EmailReader.java    From baleen with Apache License 2.0 6 votes vote down vote up
private List<String> getAttachments(Message msg) throws MessagingException, IOException {
  Object messageContentObject = msg.getContent();

  List<String> attachments = new ArrayList<>();

  if (messageContentObject instanceof Multipart) {
    Multipart multipart = (Multipart) msg.getContent();

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

      if (!Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())
          && StringUtils.isBlank(part.getFileName())) {
        continue;
      }

      attachments.add(part.getFileName());
    }
  }

  return attachments;
}
 
Example 6
Source File: ArdulinkMailMessageCountAdapter.java    From Ardulink-1 with Apache License 2.0 6 votes vote down vote up
private String getContent(Message message) throws IOException, MessagingException {

		String retvalue = "";
		
		Object msgContent = message.getContent();
		if(msgContent instanceof Multipart) {
			Multipart multipart = (Multipart)message.getContent();
			int count = multipart.getCount();
			for(int i = 0; i < count; i++) {
				BodyPart part = multipart.getBodyPart(i);
				if(part.isMimeType("text/plain")) {
					retvalue += "Part" + i + ": " + part.getContent().toString();
				}
			}
		} else {
			retvalue = msgContent.toString();
		}
		
		return retvalue;
	}
 
Example 7
Source File: BlueDragonMailWrapper.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
public cfArrayData getBodyParts(){
  try{
    cfArrayData arr = cfArrayData.createArray( 1 );

    if ( message.isMimeType("multipart/*") ){

      Multipart mp  = (Multipart)message.getContent();
      int count     = mp.getCount();
      for (int i = 0; i < count; i++)
        arr.addElement( new BlueDragonPartWrapper(mp.getBodyPart(i)) );

    }else{
      arr.addElement( new BlueDragonPartWrapper( (Part)message ) );
    }

    return arr;
  }catch(Exception e){
    return cfArrayData.createArray( 1 );
  }
}
 
Example 8
Source File: EMLTransformer.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Find "text" parts of message recursively and appends it to sb StringBuilder
 * 
 * @param multipart Multipart to process
 * @param sb StringBuilder 
 * @throws MessagingException
 * @throws IOException
 */
private void processMultiPart(Multipart multipart, StringBuilder sb) throws MessagingException, IOException
{
    boolean isAlternativeMultipart = multipart.getContentType().contains(MimetypeMap.MIMETYPE_MULTIPART_ALTERNATIVE);
    if (isAlternativeMultipart)
    {
        processAlternativeMultipart(multipart, sb);
    }
    else
    {
        for (int i = 0, n = multipart.getCount(); i < n; i++)
        {
            Part part = multipart.getBodyPart(i);
            if (part.getContent() instanceof Multipart)
            {
                processMultiPart((Multipart) part.getContent(), sb);
            }
            else
            {
                processPart(part, sb);
            }
        }
    }
}
 
Example 9
Source File: ArdulinkMailMessageCountAdapter.java    From Ardulink-1 with Apache License 2.0 5 votes vote down vote up
private boolean isMultipartValid(Message message) throws MessagingException, IOException {
	boolean retvalue = false;
	Multipart multipart = (Multipart)message.getContent();
	int count = multipart.getCount();
	for(int i = 0; i < count; i++) {
		BodyPart part = multipart.getBodyPart(i);
		if(part.isMimeType("text/plain")) {
			retvalue = true;
		}
	}
	
	return retvalue;
}
 
Example 10
Source File: EMailReceiveCustomizer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private static String getPlainTextFromMultipart(Multipart multipart)  throws MessagingException, IOException {
    StringBuilder result = new StringBuilder();
    int count = multipart.getCount();
    for (int i = 0; i < count; i++) {
        BodyPart bodyPart = multipart.getBodyPart(i);
        if (bodyPart.isMimeType(TEXT_PLAIN)) {
            result.append(NEW_LINE)
                        .append(bodyPart.getContent());
            break; // without break same text can appear twice
        } else if (bodyPart.isMimeType(TEXT_HTML)) {
            result.append(NEW_LINE)
                        .append(Jsoup.parse((String) bodyPart.getContent()).text());
            break; // without break same text can appear twice
        } else if (bodyPart.isMimeType("application/pgp-encrypted")) {
            //
            // Body is encrypted so flag as such to enable easy understanding for users
            //
            result.append(NEW_LINE)
                        .append("<pgp encrypted text>")
                        .append(NEW_LINE)
                        .append(bodyPart.getContent().toString());
        } else if (bodyPart.getContent() instanceof MimeMultipart){
            result.append(NEW_LINE)
                        .append(getPlainTextFromMultipart((MimeMultipart) bodyPart.getContent()));
        }
    }
    return result.toString();
}
 
Example 11
Source File: JavaMailSender.java    From ogham with Apache License 2.0 5 votes vote down vote up
private static Multipart findRelatedContainer(Multipart container) throws MessagingException, IOException {
	if (isRelated(container)) {
		return container;
	}
	for (int i = 0; i < container.getCount(); i++) {
		Object content = container.getBodyPart(i).getContent();
		if (content instanceof Multipart) {
			return findRelatedContainer((Multipart) content);
		}
	}
	return null;
}
 
Example 12
Source File: MailUtils.java    From scada with MIT License 5 votes vote down vote up
/** 
 * ���渽�� 
 * @param part �ʼ��ж��������е�����һ������� 
 * @param destDir  ��������Ŀ¼ 
 */ 
public static void saveAttachment(Part part, String destDir) throws UnsupportedEncodingException, MessagingException, 
        FileNotFoundException, IOException { 
    if (part.isMimeType("multipart/*")) { 
        Multipart multipart = (Multipart) part.getContent();    //�������ʼ� 
        //�������ʼ���������ʼ��� 
        int partCount = multipart.getCount(); 
        for (int i = 0; i < partCount; i++) { 
            //��ø������ʼ�������һ���ʼ��� 
            BodyPart bodyPart = multipart.getBodyPart(i); 
            //ijһ���ʼ���Ҳ�п������ɶ���ʼ�����ɵĸ����� 
            String disp = bodyPart.getDisposition(); 
            if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) { 
                InputStream is = bodyPart.getInputStream(); 
                saveFile(is, destDir, decodeText(bodyPart.getFileName())); 
            } else if (bodyPart.isMimeType("multipart/*")) { 
                saveAttachment(bodyPart,destDir); 
            } else { 
                String contentType = bodyPart.getContentType(); 
                if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) { 
                    saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName())); 
                } 
            } 
        } 
    } else if (part.isMimeType("message/rfc822")) { 
        saveAttachment((Part) part.getContent(),destDir); 
    } 
}
 
Example 13
Source File: ArdulinkMailMessageCountListener.java    From Ardulink-1 with Apache License 2.0 5 votes vote down vote up
private boolean isMultipartValid(Message message) throws MessagingException, IOException {
	boolean retvalue = false;
	Multipart multipart = (Multipart)message.getContent();
	int count = multipart.getCount();
	for(int i = 0; i < count; i++) {
		BodyPart part = multipart.getBodyPart(i);
		if(part.isMimeType("text/plain")) {
			retvalue = true;
		}
	}
	
	return retvalue;
}
 
Example 14
Source File: EmailUtils.java    From ogham with Apache License 2.0 5 votes vote down vote up
/**
 * Get a list of direct attachments that match the provided predicate.
 * 
 * @param multipart
 *            the email that contains several parts
 * @param filter
 *            the predicate used to find the attachments
 * @return the found attachments or empty list
 * @throws MessagingException
 *             when message can't be read
 */
public static List<BodyPart> getAttachments(Multipart multipart, Predicate<Part> filter) throws MessagingException {
	if (multipart == null) {
		throw new IllegalStateException("The multipart can't be null");
	}
	List<BodyPart> found = new ArrayList<>();
	for (int i = 0; i < multipart.getCount(); i++) {
		BodyPart bodyPart = multipart.getBodyPart(i);
		if (filter.test(bodyPart)) {
			found.add(bodyPart);
		}
	}
	return found;
}
 
Example 15
Source File: ZhilianEmailResumeParser.java    From job with MIT License 5 votes vote down vote up
protected Document parse2Html(File file) throws Exception {
  InputStream in = new FileInputStream(file);

  Session mailSession = Session.getDefaultInstance(System.getProperties(), null);

  MimeMessage msg = new MimeMessage(mailSession, in);

  Multipart part = (Multipart) msg.getContent();
  String html = "";
  for(int i = 0; i < part.getCount(); i++) {
    BodyPart body = part.getBodyPart(i);
    String type = body.getContentType();
    if(type.startsWith("text/html")) {
      html = body.getContent().toString();
      break;
    }
  }
  in.close();
  
  if(html == null || html.length() == 0) {
    String content = FileUtils.readFileToString(file);
    final String endFlag = "</html>";
    int start = content.indexOf("<html");
    int end = content.indexOf(endFlag);
    content = content.substring(start, end + endFlag.length());
    html = QuotedPrintableUtils.decode(content.getBytes(), "gb2312");
    System.err.println(html);
  }
  return Jsoup.parse(html);
}
 
Example 16
Source File: MessageHelper.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
static void overrideContentTransferEncoding(Multipart mp) throws MessagingException, IOException {
    for (int i = 0; i < mp.getCount(); i++) {
        Part part = mp.getBodyPart(i);
        Object content = part.getContent();
        if (content instanceof Multipart) {
            part.setHeader("Content-Transfer-Encoding", "7bit");
            overrideContentTransferEncoding((Multipart) content);
        } else
            part.setHeader("Content-Transfer-Encoding", "base64");
    }
}
 
Example 17
Source File: MailConnection.java    From hop with Apache License 2.0 5 votes vote down vote up
private void handleMultipart( String foldername, Multipart multipart, Pattern pattern ) throws HopException {
  try {
    for ( int i = 0, n = multipart.getCount(); i < n; i++ ) {
      handlePart( foldername, multipart.getBodyPart( i ), pattern );
    }
  } catch ( Exception e ) {
    throw new HopException( e );
  }
}
 
Example 18
Source File: AttachmentsExtractor.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void extractAttachments(NodeRef messageRef, MimeMessage originalMessage) throws IOException, MessagingException
{
    NodeRef attachmentsFolderRef = null;
    String attachmentsFolderName = null;
    boolean createFolder = false;
    switch (attachmentsExtractorMode)
    {
    case SAME:
        attachmentsFolderRef = nodeService.getPrimaryParent(messageRef).getParentRef();
        break;
    case COMMON:
        attachmentsFolderRef = this.attachmentsFolderRef;
        break;
    case SEPARATE:
    default:
        String messageName = (String) nodeService.getProperty(messageRef, ContentModel.PROP_NAME);
        attachmentsFolderName = messageName + "-attachments";
        createFolder = true;
        break;
    }
    if (!createFolder)
    {
        nodeService.createAssociation(messageRef, attachmentsFolderRef, ImapModel.ASSOC_IMAP_ATTACHMENTS_FOLDER);
    }
 
    Object content = originalMessage.getContent();
    if (content instanceof Multipart)
    {
        Multipart multipart = (Multipart) content;
 
        for (int i = 0, n = multipart.getCount(); i < n; i++)
        {
            Part part = multipart.getBodyPart(i);
            if ("attachment".equalsIgnoreCase(part.getDisposition()))
            {
                if (createFolder)
                {
                    attachmentsFolderRef = createAttachmentFolder(messageRef, attachmentsFolderName);
                    createFolder = false;
                }
                createAttachment(messageRef, attachmentsFolderRef, part);
            }
        }
    }
 
}
 
Example 19
Source File: ClassifyBounce.java    From james-project with Apache License 2.0 4 votes vote down vote up
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;
            }

            return s;
        }
 
Example 20
Source File: TableLoaderInbox.java    From hana-native-adapters with Apache License 2.0 4 votes vote down vote up
@Override
protected void setColumnValue(int tablecolumnindex, int returncolumnindex, AdapterRow row, Object o) throws AdapterException {
	Message msg = (Message) o;
	try {
    	switch (tablecolumnindex) {
    	case 0:
    		Address from;
    		if (msg.getFrom().length > 0) {
    			from = msg.getFrom()[0];
	    		row.setColumnValue(returncolumnindex, checkLength(from.toString(), 127));
    		} else {
	    		row.setColumnNull(returncolumnindex);
    		}
    		break;
    	case 1:
    		row.setColumnValue(returncolumnindex, checkLength(msg.getSubject(), 512));
    		break;
    	case 2:
    		row.setColumnValue(returncolumnindex, new Timestamp(msg.getReceivedDate()));
    		break;
    	case 3:
    		row.setColumnValue(returncolumnindex, new Timestamp(msg.getSentDate()));
    		break;
    	case 4:
    		row.setColumnValue(returncolumnindex, checkLength(msg.getContentType(), 127));
    		break;
    	case 5:
    		row.setColumnValue(returncolumnindex, msg.getSize());
    		break;
    	case 6:
    		Address reply;
    		if (msg.getReplyTo() != null && msg.getReplyTo().length > 0) {
    			reply = msg.getReplyTo()[0];
    			row.setColumnValue(returncolumnindex, checkLength(reply.toString(), 1024));
    		} else {
    			row.setColumnNull(returncolumnindex);
    		}
    		break;
    	case 7:
    		Object contentObj = msg.getContent();
    		String resultString = null;
    		if (contentObj instanceof Multipart) {
    			BodyPart clearTextPart = null;
    			BodyPart htmlTextPart = null;
    			Multipart content = (Multipart)contentObj;
    			int count = content.getCount();
    			for(int i=0; i<count; i++)
    			{
    				BodyPart part =  content.getBodyPart(i);
    				if (part.isMimeType("text/plain")) {
    					clearTextPart = part;
    					break;
    				}
    				else if(part.isMimeType("text/html")) {
    					htmlTextPart = part;
    				}
    			}

    			if (clearTextPart != null) {
    				resultString = (String) clearTextPart.getContent();
    			} else if (htmlTextPart != null) {
    				String html = (String) htmlTextPart.getContent();
    				resultString = Jsoup.parse(html).text();
    			}

    		} else if (contentObj instanceof String) {
    			if (msg.getContentType().startsWith("text/html")) {
    				resultString = Jsoup.parse((String) contentObj).text();
    			} else {
    				resultString = (String) contentObj;
    			}
    		} else {
    			resultString = contentObj.toString();
    		}
    		row.setColumnValue(returncolumnindex, checkLength(resultString, 5000));
    		break;
    	}		
	} catch (MessagingException | IOException e) {
		throw new AdapterException(e);
	}
}