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

The following examples show how to use javax.mail.Multipart#getBodyPart() . 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: ArdulinkMailMessageCountListener.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 3
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 4
Source File: TextCalendarBodyToAttachmentTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
public void contentDispositionOfAttachmentShouldBeOverwrittenWhenOriginalMessageHasContentDisposition() throws Exception {
    String messageContent = "Content-type: text/calendar; method=REPLY; charset=UTF-8\n" +
        "Content-Disposition: inline\n" +
        "\n" +
        "BEGIN:VCALENDAR\n" +
        "END:VEVENT\n" +
        "END:VCALENDAR";
    MimeMessage message = MimeMessageUtil.mimeMessageFromString(messageContent);

    Mail mail = FakeMail.builder()
        .name("name")
        .mimeMessage(message)
        .build();

    mailet.service(mail);

    Multipart multipart = (Multipart)mail.getMessage().getContent();

    int firstBodyPartIndex = 0;
    BodyPart firstBodyPart = multipart.getBodyPart(firstBodyPartIndex);
    assertThat(firstBodyPart.getHeader("Content-Disposition")).containsExactly("attachment");
}
 
Example 5
Source File: Mail.java    From camunda-bpm-mail with Apache License 2.0 6 votes vote down vote up
protected static void processMessageContent(Message message, Mail mail) throws MessagingException, IOException {

    if (isMultipartMessage(message)) {
      Multipart multipart = (Multipart) message.getContent();

      int numberOfParts = multipart.getCount();
      for (int partCount = 0; partCount < numberOfParts; partCount++) {
        BodyPart bodyPart = multipart.getBodyPart(partCount);

        processMessagePartContent(bodyPart, mail);
      }

    } else {
      processMessagePartContent(message, mail);
    }
  }
 
Example 6
Source File: MailUtils.java    From scada with MIT License 6 votes vote down vote up
/**
 * ����ʼ��ı�����
 * @param part �ʼ���
 * @param content �洢�ʼ��ı����ݵ��ַ���
 */ 
public static void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException { 
    //������ı����͵ĸ�����ͨ��getContent��������ȡ���ı����ݣ����ⲻ��������Ҫ�Ľ��������������Ҫ���ж� 
    boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;  
    if (part.isMimeType("text/*") && !isContainTextAttach) { 
        content.append(part.getContent().toString()); 
    } else if (part.isMimeType("message/rfc822")) {  
        getMailTextContent((Part)part.getContent(),content); 
    } else 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); 
            getMailTextContent(bodyPart,content); 
        } 
    } 
}
 
Example 7
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 8
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 9
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 10
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 11
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 12
Source File: TextCalendarBodyToAttachmentTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void contentTypeOfAttachmentShouldBeTakenFromOriginalMessage() throws Exception {
    Mail mail = FakeMail.builder()
        .name("name")
        .mimeMessage(calendarMessage)
        .build();

    mailet.service(mail);

    Multipart multipart = (Multipart)mail.getMessage().getContent();

    int firstBodyPartIndex = 0;
    BodyPart firstBodyPart = multipart.getBodyPart(firstBodyPartIndex);
    assertThat(firstBodyPart.getContentType()).isEqualTo("text/calendar; method=REPLY; charset=UTF-8");
}
 
Example 13
Source File: TextCalendarBodyToAttachmentTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void contentTransferEncodingOfAttachmentShouldBeTakenFromOriginalMessage() throws Exception {
    Mail mail = FakeMail.builder()
        .name("name")
        .mimeMessage(calendarMessage)
        .build();

    mailet.service(mail);

    Multipart multipart = (Multipart)mail.getMessage().getContent();

    int firstBodyPartIndex = 0;
    BodyPart firstBodyPart = multipart.getBodyPart(firstBodyPartIndex);
    assertThat(firstBodyPart.getHeader("Content-transfer-encoding")).containsExactly("8BIT");
}
 
Example 14
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 15
Source File: EmailDataFactory.java    From bobcat with Apache License 2.0 5 votes vote down vote up
private StringBuilder processMultipart(final Multipart multipart)
    throws MessagingException,
    IOException {
  StringBuilder messageContent = new StringBuilder();
  Part part;
  for (int i = 0; i < multipart.getCount(); i++) {
    part = multipart.getBodyPart(i);
    if (part.getContent() instanceof Multipart) {
      messageContent.append(processMultipart((Multipart) part.getContent()));
    } else if (isPartTextLike(part)) {
      messageContent.append(part.getContent()).append('\n');
    }
  }
  return messageContent;
}
 
Example 16
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 17
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 18
Source File: Pop3Util.java    From anyline with Apache License 2.0 4 votes vote down vote up
/** 
 * 保存附件 
 *  
 * @param part  邮件中多个组合体中的其中一个组合体 
 * @param dir  附件保存目录 
 * @param sendTime sendTime
 * @param files files
 * @throws UnsupportedEncodingException UnsupportedEncodingException 
 * @throws MessagingException MessagingException 
 * @throws FileNotFoundException FileNotFoundException 
 * @throws IOException  IOException
 * @return List
 */ 

public static List<File> downloadAttachment(Part part, String dir, Date sendTime, List<File> files) throws UnsupportedEncodingException, MessagingException, FileNotFoundException, IOException { 
	if (BasicUtil.isEmpty(files)) { 
		files = new ArrayList<File>(); 
	} 
	dir = dir.replace("{send_date}", DateUtil.format(sendTime,"yyyyMMdd")); 
	dir = dir.replace("{send_time}", DateUtil.format(sendTime,"yyyyMMddhhmmss")); 
	if (part.isMimeType("multipart/*")) { 
		Multipart multipart = (Multipart) part.getContent(); // 复杂体邮件 
		int partCount = multipart.getCount(); 
		for (int i = 0; i < partCount; i++) { 
			boolean result = false; 
			BodyPart bodyPart = multipart.getBodyPart(i); 
			String disp = bodyPart.getDisposition(); 
			String name = decode(bodyPart.getFileName()); 
			String path = null; 
			if(dir.contains("{file}")){ 
				path = dir.replace("{file}", name); 
			}else{ 
				path = FileUtil.mergePath(dir, name); 
			} 
			File file =  new File(path); 
			if (BasicUtil.isNotEmpty(name) && disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) { 
				result = FileUtil.save(bodyPart.getInputStream(), file); 
			} else if (bodyPart.isMimeType("multipart/*")) { 
				downloadAttachment(bodyPart, dir, sendTime, files); 
			} else if(BasicUtil.isNotEmpty(name)){ 
				String contentType = bodyPart.getContentType(); 
				if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) { 
					result = FileUtil.save(bodyPart.getInputStream(), file); 
				} 
			} 
			if (result) { 
				files.add(file); 
			} 
		} 
	} else if (part.isMimeType("message/rfc822")) { 
		downloadAttachment((Part) part.getContent(), dir, sendTime, files); 
	} 
	return files; 
}
 
Example 19
Source File: AttachmentFileNameIs.java    From james-project with Apache License 2.0 4 votes vote down vote up
/**
 * Checks if <I>part</I> matches with at least one of the <CODE>masks</CODE>.
 * 
 * @param part
 */
protected boolean matchFound(Part part) throws Exception {
    
    /*
     * if there is an attachment and no inline text,
     * the content type can be anything
     */
    
    if (part.getContentType() == null ||
        part.getContentType().startsWith("multipart/alternative")) {
        return false;
    }
    
    Object content;
    
    try {
        content = part.getContent();
    } catch (UnsupportedEncodingException uee) {
        // in this case it is not an attachment, so ignore it
        return false;
    }
    
    Exception anException = null;
    
    if (content instanceof Multipart) {
        Multipart multipart = (Multipart) content;
        for (int i = 0; i < multipart.getCount(); i++) {
            try {
                Part bodyPart = multipart.getBodyPart(i);
                if (matchFound(bodyPart)) {
                    return true; // matching file found
                }
            } catch (MessagingException e) {
                anException = e;
            } // remember any messaging exception and process next bodypart
        }
    } else {
        String fileName = part.getFileName();
        if (fileName != null) {
            fileName = cleanFileName(fileName);
            // check the file name
            if (matchFound(fileName)) {
                if (isDebug) {
                    LOGGER.debug("matched {}", fileName);
                }
                return true;
            }
            if (unzipIsRequested && fileName.endsWith(ZIP_SUFFIX) && matchFoundInZip(part)) {
                return true;
            }
        }
    }
    
    // if no matching attachment was found and at least one exception was catched rethrow it up
    if (anException != null) {
        throw anException;
    }
    
    return false;
}
 
Example 20
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);
            }
        }
    }
 
}