Java Code Examples for javax.mail.BodyPart#isMimeType()

The following examples show how to use javax.mail.BodyPart#isMimeType() . 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: EmailAccount.java    From teammates with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the text from multipart/alternative, the type of text returned follows the preference of the sending agent.
 */
private String getTextFromMultiPartAlternative(Multipart multipart) throws IOException, MessagingException {
    // search in reverse order as a multipart/alternative should have their most preferred format last
    for (int i = multipart.getCount() - 1; i >= 0; i--) {
        BodyPart bodyPart = multipart.getBodyPart(i);

        if (bodyPart.isMimeType("text/html")) {
            return (String) bodyPart.getContent();
        } else if (bodyPart.isMimeType("text/plain")) {
            // Since we are looking in reverse order, if we did not encounter a text/html first we can return the plain
            // text because that is the best preferred format that we understand. If a text/html comes along later it
            // means the agent sending the email did not set the html text as preferable or did not set their preferred
            // order correctly, and in that case we do not handle that.
            return (String) bodyPart.getContent();
        } else if (bodyPart.isMimeType("multipart/*") || bodyPart.isMimeType("message/rfc822")) {
            String text = getTextFromPart(bodyPart);
            if (text != null) {
                return text;
            }
        }
    }
    // we do not know how to handle the text in the multipart or there is no text
    return null;
}
 
Example 3
Source File: MailerImplTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private String getTextFromMimeMultipart(
        MimeMultipart mimeMultipart) throws MessagingException, IOException {
    StringBuilder result = new StringBuilder();
    int count = mimeMultipart.getCount();
    for (int i = 0; i < count; i++) {
        BodyPart bodyPart = mimeMultipart.getBodyPart(i);
        if (bodyPart.isMimeType(TEXT_CONTENT_TYPE)) {
            result.append("\n").append(bodyPart.getContent());
            break; // without break same text appears twice in my tests
        } else if (bodyPart.isMimeType("text/html")) {
            result.append("\n").append(bodyPart.getContent());
        } else if (bodyPart.getContent() instanceof MimeMultipart) {
            result.append(getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent()));
        }
    }
    return result.toString();
}
 
Example 4
Source File: MailSteps.java    From NoraUi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * @param mimeMultipart
 * @return
 * @throws MessagingException
 * @throws IOException
 */
private static String getTextFromMimeMultipart(MimeMultipart mimeMultipart) throws MessagingException, IOException {
    final StringBuilder result = new StringBuilder();
    final int count = mimeMultipart.getCount();
    for (int i = 0; i < count; i++) {
        final BodyPart bodyPart = mimeMultipart.getBodyPart(i);
        if (bodyPart.isMimeType("text/plain")) {
            result.append("\n");
            result.append(bodyPart.getContent());
        } else if (bodyPart.isMimeType("text/html")) {
            result.append("\n");
            result.append((String) bodyPart.getContent());
        } else if (bodyPart.getContent() instanceof MimeMultipart) {
            result.append(getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent()));
        }
    }
    return result.toString();
}
 
Example 5
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 6
Source File: ReadEmailImap.java    From opentest with MIT License 6 votes vote down vote up
/**
 * Extracts the text content from a multipart email message.
 */
private String getTextFromMimeMultipart(MimeMultipart mimeMultipart) throws Exception {
    ArrayList<String> partStrings = new ArrayList<>();
    
    int partCount = mimeMultipart.getCount();
    for (int i = 0; i < partCount; i++) {
        BodyPart bodyPart = mimeMultipart.getBodyPart(i);
        if (bodyPart.isMimeType("text/plain")) {
            partStrings.add((String)bodyPart.getContent());
        } else if (bodyPart.isMimeType("text/html")) {
            partStrings.add((String)bodyPart.getContent());
        } else if (bodyPart.getContent() instanceof MimeMultipart) {
            partStrings.add(getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent()));
        }
    }
    
    return String.join("\n", partStrings);
}
 
Example 7
Source File: NntpUtil.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
private static String getBodyPart(MimeMultipart mimeMultiPart) throws IOException, MessagingException
{
	for(int i=0; i<mimeMultiPart.getCount(); i++)
	{
		BodyPart bodyPart = mimeMultiPart.getBodyPart(i); 
		if(bodyPart.isMimeType("text/plain"))
		{
			return (String) bodyPart.getContent();
		}
		else if(bodyPart.getContent() instanceof MimeMultipart)
		{
			return getBodyPart((MimeMultipart)bodyPart.getContent());
		}
	}
	return "";
}
 
Example 8
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 9
Source File: MailReceiverUtils.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
private String getTextFromMimeMultipart(MimeMultipart mimeMultipart)
    throws MessagingException, IOException {
  StringBuilder result = new StringBuilder();
  int count = mimeMultipart.getCount();
  for (int i = 0; i < count; i++) {
    BodyPart bodyPart = mimeMultipart.getBodyPart(i);
    if (bodyPart.isMimeType("text/plain")) {
      result.append("\n").append(bodyPart.getContent());
    } else if (bodyPart.isMimeType("text/html")) {
      result.append("\n").append((String) bodyPart.getContent());
    } else if (bodyPart.getContent() instanceof MimeMultipart) {
      result.append(getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent()));
    }
  }
  return result.toString();
}
 
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: 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 12
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 13
Source File: Pop3Util.java    From anyline with Apache License 2.0 5 votes vote down vote up
/** 
 * 判断邮件中是否包含附件 
 *  
 * @param part part 
 * @return 邮件中存在附件返回true,不存在返回false 
 * @throws MessagingException MessagingException
 * @throws IOException IOException
 * @return boolean
 */
public static boolean isContainAttachment(Part part)  throws MessagingException, IOException { 
	boolean flag = false; 
	if (part.isMimeType("multipart/*")) { 
		MimeMultipart multipart = (MimeMultipart) part.getContent(); 
		int partCount = multipart.getCount(); 
		for (int i = 0; i < partCount; i++) { 
			BodyPart bodyPart = multipart.getBodyPart(i); 
			String disp = bodyPart.getDisposition(); 
			if (disp != null 
					&& (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp 
							.equalsIgnoreCase(Part.INLINE))) { 
				flag = true; 
			} else if (bodyPart.isMimeType("multipart/*")) { 
				flag = isContainAttachment(bodyPart); 
			} else { 
				String contentType = bodyPart.getContentType(); 
				if (contentType.indexOf("application") != -1) { 
					flag = true; 
				} 

				if (contentType.indexOf("name") != -1) { 
					flag = true; 
				} 
			} 

			if (flag) 
				break; 
		} 
	} else if (part.isMimeType("message/rfc822")) { 
		flag = isContainAttachment((Part) part.getContent()); 
	} 
	return flag; 
}
 
Example 14
Source File: MailUtils.java    From scada with MIT License 5 votes vote down vote up
/**
 * �ж��ʼ����Ƿ��������
 * @param msg �ʼ�����
 * @return �ʼ��д��ڸ�������true�������ڷ���false
 */ 
public static boolean isContainAttachment(Part part) throws MessagingException, IOException { 
    boolean flag = false; 
    if (part.isMimeType("multipart/*")) { 
        MimeMultipart multipart = (MimeMultipart) part.getContent(); 
        int partCount = multipart.getCount(); 
        for (int i = 0; i < partCount; i++) { 
            BodyPart bodyPart = multipart.getBodyPart(i); 
            String disp = bodyPart.getDisposition(); 
            if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) { 
                flag = true; 
            } else if (bodyPart.isMimeType("multipart/*")) { 
                flag = isContainAttachment(bodyPart); 
            } else { 
                String contentType = bodyPart.getContentType(); 
                if (contentType.indexOf("application") != -1) { 
                    flag = true; 
                }   
                 
                if (contentType.indexOf("name") != -1) { 
                    flag = true; 
                }  
            } 
             
            if (flag) break; 
        } 
    } else if (part.isMimeType("message/rfc822")) { 
        flag = isContainAttachment((Part)part.getContent()); 
    } 
    return flag; 
}
 
Example 15
Source File: MailManager.java    From vpn-over-dns with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private String getMultipartContentString(final MimeMultipart multipart, final boolean mixed) throws IOException, MessagingException {
	// content-type: multipart/mixed ou multipart/alternative

	final StringBuffer selected_content = new StringBuffer();
	for (int i = 0; i < multipart.getCount(); i++) {
		final BodyPart body_part = multipart.getBodyPart(i);
		final Object content = body_part.getContent();

		final String content_string;
		if (String.class.isInstance(content))
			if (body_part.isMimeType("text/html")) content_string = GenericTools.html2Text((String) content);
			else if (body_part.isMimeType("text/plain")) content_string = (String) content;
			else {
				log.warn("body part content-type not handled: " + body_part.getContentType() + " -> downgrading to String");
				content_string = (String) content;
			}
		else if (MimeMultipart.class.isInstance(content)) {
			boolean part_mixed = false;
			if (body_part.isMimeType("multipart/mixed")) part_mixed = true;
			else if (body_part.isMimeType("multipart/alternative")) part_mixed = false;
			else {
				log.warn("body part content-type not handled: " + body_part.getContentType() + " -> downgrading to multipart/mixed");
				part_mixed = true;
			}
			content_string = getMultipartContentString((MimeMultipart) content, part_mixed);
		} else {
			log.warn("invalid body part content type and class: " + content.getClass().toString() + " - " + body_part.getContentType());
			content_string = "";
		}

		if (mixed == false) {
			// on sélectionne la première part non vide - ce n'est pas forcément la meilleure alternative, mais comment différentiel un text/plain d'une pièce jointe d'un text/plain du corps du message, accompagnant un text/html du même corps ???
			if (selected_content.length() == 0) selected_content.append(content_string);
		} else {
			if (selected_content.length() > 0 && content_string.length() > 0) selected_content.append("\r\n---\r\n");
			selected_content.append(content_string);
		}
	}
	return selected_content.toString();
}
 
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: 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);
	}
}
 
Example 18
Source File: StripAttachment.java    From james-project with Apache License 2.0 4 votes vote down vote up
private boolean isMatching(BodyPart bodyPart, String fileName) throws MessagingException {
    return fileNameMatches(fileName) || bodyPart.isMimeType(mimeType);
}
 
Example 19
Source File: ICSSanitizer.java    From james-project with Apache License 2.0 4 votes vote down vote up
private boolean needsSanitizing(BodyPart bodyPart) throws MessagingException {
    return bodyPart.isMimeType("text/calendar") && bodyPart.getSize() <= 0;
}
 
Example 20
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; 
}