Java Code Examples for javax.mail.internet.MimeMultipart#getCount()
The following examples show how to use
javax.mail.internet.MimeMultipart#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: MailReceiverUtils.java From codenvy with Eclipse Public License 1.0 | 6 votes |
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 2
Source File: MailSteps.java From NoraUi with GNU Affero General Public License v3.0 | 6 votes |
/** * @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 3
Source File: MimePackage.java From ats-framework with Apache License 2.0 | 6 votes |
private String addContentTrace( Object content, String level ) throws MessagingException { final String level1 = level; final String level2 = "\t" + level1; StringBuilder msg = new StringBuilder(); if (content instanceof String) { msg.append(level2 + "BODY STRING START:\n"); msg.append((String) content); msg.append(level2 + "BODY STRING END:\n"); } else if (content instanceof MimeMultipart) { MimeMultipart multipart = (MimeMultipart) content; for (int i = 0; i < multipart.getCount(); i++) { msg.append(addBodyPartTrace(multipart.getBodyPart(i), level2)); } } else { msg.append(level2 + "*** CANNOT CONVERT UNSUPPORTED CONTENT: " + content.getClass().getCanonicalName() + " ***\n"); } return msg.toString(); }
Example 4
Source File: ReadEmailImap.java From opentest with MIT License | 6 votes |
/** * 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 5
Source File: GreenMailUtil.java From greenmail with Apache License 2.0 | 6 votes |
public static boolean hasNonTextAttachments(Part m) { try { Object content = m.getContent(); if (content instanceof MimeMultipart) { MimeMultipart mm = (MimeMultipart) content; for (int i = 0; i < mm.getCount(); i++) { BodyPart p = mm.getBodyPart(i); if (hasNonTextAttachments(p)) { return true; } } return false; } else { return !m.getContentType().trim().toLowerCase().startsWith("text"); } } catch (Exception e) { throw new IllegalArgumentException(e); } }
Example 6
Source File: MailServer.java From keycloak with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { ServerSetup setup = new ServerSetup(3025, "localhost", "smtp"); GreenMail greenMail = new GreenMail(setup); greenMail.start(); System.out.println("Started mail server (localhost:3025)"); System.out.println(); while (true) { int c = greenMail.getReceivedMessages().length; if (greenMail.waitForIncomingEmail(Long.MAX_VALUE, c + 1)) { MimeMessage message = greenMail.getReceivedMessages()[c++]; System.out.println("-------------------------------------------------------"); System.out.println("Received mail to " + message.getRecipients(RecipientType.TO)[0]); if (message.getContent() instanceof MimeMultipart) { MimeMultipart mimeMultipart = (MimeMultipart) message.getContent(); for (int i = 0; i < mimeMultipart.getCount(); i++) { System.out.println("----"); System.out.println(mimeMultipart.getBodyPart(i).getContentType() + ":"); System.out.println(); System.out.println(mimeMultipart.getBodyPart(i).getContent()); } } else { System.out.println(); System.out.println(message.getContent()); } System.out.println("-------------------------------------------------------"); } } }
Example 7
Source File: URIRBLHandler.java From james-project with Apache License 2.0 | 5 votes |
/** * Recursively scans all MimeParts of an email for domain strings. Domain * strings that are found are added to the supplied HashSet. * * @param part * MimePart to scan * @param session * not null * @return domains The HashSet that contains the domains which were * extracted */ private HashSet<String> scanMailForDomains(MimePart part, SMTPSession session) throws MessagingException, IOException { HashSet<String> domains = new HashSet<>(); LOGGER.debug("mime type is: \"{}\"", part.getContentType()); if (part.isMimeType("text/plain") || part.isMimeType("text/html")) { LOGGER.debug("scanning: \"{}\"", part.getContent()); HashSet<String> newDom = URIScanner.scanContentForDomains(domains, part.getContent().toString()); // Check if new domains are found and add the domains if (newDom != null && newDom.size() > 0) { domains.addAll(newDom); } } else if (part.isMimeType("multipart/*")) { MimeMultipart multipart = (MimeMultipart) part.getContent(); int count = multipart.getCount(); LOGGER.debug("multipart count is: {}", count); for (int index = 0; index < count; index++) { LOGGER.debug("recursing index: {}", index); MimeBodyPart mimeBodyPart = (MimeBodyPart) multipart.getBodyPart(index); HashSet<String> newDomains = scanMailForDomains(mimeBodyPart, session); // Check if new domains are found and add the domains if (newDomains != null && newDomains.size() > 0) { domains.addAll(newDomains); } } } return domains; }
Example 8
Source File: MessageToCoreToMessage.java From james-project with Apache License 2.0 | 5 votes |
protected static String getScript(MimeMessage message) throws IOException, MessagingException { String result = null; if (message.getContentType().startsWith("multipart/")) { MimeMultipart parts = (MimeMultipart) message.getContent(); boolean found = false; // Find the first part with any of: // - an attachment type of "application/sieve" // - a file suffix of ".siv" // - a file suffix of ".sieve" for (int i = 0; !found && i < parts.getCount(); i++) { MimeBodyPart part = (MimeBodyPart) parts.getBodyPart(i); found = part.isMimeType("application/sieve"); if (!found) { String fileName = null == part.getFileName() ? null : part.getFileName().toLowerCase(Locale.US); found = fileName != null && (fileName.endsWith(".siv") || fileName.endsWith(".sieve")); } if (found) { Object content = part.getContent(); if (content instanceof String) { return (String) part.getContent(); } InputStream is = (InputStream) part.getContent(); try (Scanner scanner = new Scanner(is, "UTF-8")) { scanner.useDelimiter("\\A"); if (scanner.hasNext()) { result = scanner.next(); } } } } } if (null == result) { throw new MessagingException("Script part not found in this message"); } return result; }
Example 9
Source File: EmailSteps.java From datamill with ISC License | 5 votes |
private String getCompleteContent(Message message) throws IOException, MessagingException { StringBuilder completeContent = new StringBuilder(); MimeMultipart contents = (MimeMultipart) message.getContent(); for (int i = 0; i < contents.getCount(); i++) { BodyPart part = contents.getBodyPart(i); String partText = getPartTextContent(part); completeContent.append(partText); } return completeContent.toString(); }
Example 10
Source File: ContentEngineConfiguratorTest.java From flowable-engine with Apache License 2.0 | 5 votes |
@Test public void testSendMailWithContentItemAttachments() throws Exception { processEngine.getRepositoryService().createDeployment() .addClasspathResource("org/flowable/content/engine/configurator/test/ContentEngineConfiguratorTest.testSendMailWithContentItemAttachments.bpmn20.xml") .deploy(); processEngine.getRuntimeService().startProcessInstanceByKey("testSendEmailWithAttachments"); List<WiserMessage> messages = wiser.getMessages(); assertThat(messages).hasSize(1); WiserMessage message = messages.get(0); MimeMultipart mm = (MimeMultipart) message.getMimeMessage().getContent(); Set<String> contentTypes = new HashSet<>(); Set<String> names = new HashSet<>(); for (int i = 0; i < mm.getCount(); i++) { String contentTypeHeader = mm.getBodyPart(i).getHeader("Content-Type")[0]; if (contentTypeHeader.contains("name")) { contentTypeHeader = contentTypeHeader .replace("\r", "") .replace("\n", "") .replace("\t", ""); int index = contentTypeHeader.indexOf("name="); int semicolonIndex = contentTypeHeader.indexOf(";"); contentTypes.add(contentTypeHeader.substring(0, Math.min(semicolonIndex, index))); names.add(contentTypeHeader.substring(index + 5)); } } assertThat(names).containsAll(TestAttachmentBean.TEST_NAMES); assertThat(contentTypes).containsAll(TestAttachmentBean.TEST_MIME_TYPES); }
Example 11
Source File: MailUtils.java From scada with MIT License | 5 votes |
/** * �ж��ʼ����Ƿ�������� * @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 12
Source File: MailManager.java From vpn-over-dns with BSD 3-Clause "New" or "Revised" License | 5 votes |
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 13
Source File: Pop3Util.java From anyline with Apache License 2.0 | 5 votes |
/** * 判断邮件中是否包含附件 * * @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: MailerImplTest.java From quarkus with Apache License 2.0 | 5 votes |
private List<String> getContentTypesFromMimeMultipart( MimeMultipart mimeMultipart) throws MessagingException, IOException { List<String> types = new ArrayList<>(); int count = mimeMultipart.getCount(); for (int i = 0; i < count; i++) { BodyPart bodyPart = mimeMultipart.getBodyPart(i); if (bodyPart.getContent() instanceof MimeMultipart) { types.addAll(getContentTypesFromMimeMultipart((MimeMultipart) bodyPart.getContent())); } else { types.add(bodyPart.getContentType()); } } return types; }
Example 15
Source File: HttpSender.java From iaf with Apache License 2.0 | 5 votes |
public static String handleMultipartResponse(String mimeType, InputStream inputStream, IPipeLineSession session, HttpResponseHandler httpHandler) throws IOException, SenderException { String result = null; try { InputStreamDataSource dataSource = new InputStreamDataSource(mimeType, inputStream); MimeMultipart mimeMultipart = new MimeMultipart(dataSource); for (int i = 0; i < mimeMultipart.getCount(); i++) { BodyPart bodyPart = mimeMultipart.getBodyPart(i); boolean lastPart = mimeMultipart.getCount() == i + 1; if (i == 0) { String charset = Misc.DEFAULT_INPUT_STREAM_ENCODING; ContentType contentType = ContentType.parse(bodyPart.getContentType()); if(contentType.getCharset() != null) charset = contentType.getCharset().name(); InputStream bodyPartInputStream = bodyPart.getInputStream(); result = Misc.streamToString(bodyPartInputStream, charset); if (lastPart) { bodyPartInputStream.close(); } } else { // When the last stream is read the // httpMethod.releaseConnection() can be called, hence pass // httpMethod to ReleaseConnectionAfterReadInputStream. session.put("multipart" + i, new ReleaseConnectionAfterReadInputStream( lastPart ? httpHandler : null, bodyPart.getInputStream())); } } } catch(MessagingException e) { throw new SenderException("Could not read mime multipart response", e); } return result; }
Example 16
Source File: MailerImplTest.java From quarkus with Apache License 2.0 | 5 votes |
private String getAttachment(String name, MimeMultipart multipart) throws IOException, MessagingException { for (int i = 0; i < multipart.getCount(); i++) { BodyPart bodyPart = multipart.getBodyPart(i); if (bodyPart.getFileName() != null && bodyPart.getFileName().equalsIgnoreCase(name)) { assertThat(bodyPart.getContentType()).startsWith(TEXT_CONTENT_TYPE); return read(bodyPart); } } return null; }
Example 17
Source File: ImapConnection.java From davmail with GNU General Public License v2.0 | 5 votes |
protected void appendBodyStructure(StringBuilder buffer, MimeMultipart multiPart) throws IOException, MessagingException { buffer.append('('); for (int i = 0; i < multiPart.getCount(); i++) { MimeBodyPart bodyPart = (MimeBodyPart) multiPart.getBodyPart(i); try { Object mimeBody = bodyPart.getContent(); if (mimeBody instanceof MimeMultipart) { appendBodyStructure(buffer, (MimeMultipart) mimeBody); } else { // no multipart, single body appendBodyStructure(buffer, bodyPart); } } catch (UnsupportedEncodingException e) { LOGGER.warn(e); // failover: send default bodystructure buffer.append("(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\") NIL NIL NIL NIL NIL)"); } catch (MessagingException me) { DavGatewayTray.warn(me); // failover: send default bodystructure buffer.append("(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\") NIL NIL NIL NIL NIL)"); } } int slashIndex = multiPart.getContentType().indexOf('/'); if (slashIndex < 0) { throw new DavMailException("EXCEPTION_INVALID_CONTENT_TYPE", multiPart.getContentType()); } int semiColonIndex = multiPart.getContentType().indexOf(';'); if (semiColonIndex < 0) { buffer.append(" \"").append(multiPart.getContentType().substring(slashIndex + 1).toUpperCase()).append("\")"); } else { buffer.append(" \"").append(multiPart.getContentType().substring(slashIndex + 1, semiColonIndex).trim().toUpperCase()).append("\")"); } }
Example 18
Source File: MailServer.java From keycloak with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { MailServer.start(); MailServer.createEmailAccount("[email protected]", "password"); try { while (true) { int c = greenMail.getReceivedMessages().length; if (greenMail.waitForIncomingEmail(Long.MAX_VALUE, c + 1)) { MimeMessage m = greenMail.getReceivedMessages()[c++]; log.info("-------------------------------------------------------"); log.info("Received mail to " + m.getRecipients(RecipientType.TO)[0]); if (m.getContent() instanceof MimeMultipart) { MimeMultipart mimeMultipart = (MimeMultipart) m.getContent(); for (int i = 0; i < mimeMultipart.getCount(); i++) { log.info("----"); log.info(mimeMultipart.getBodyPart(i).getContentType() + ":\n"); log.info(mimeMultipart.getBodyPart(i).getContent()); } } else { log.info("\n" + m.getContent()); } log.info("-------------------------------------------------------"); } } } catch (IOException | InterruptedException | MessagingException ex) { throw new RuntimeException(ex); } }
Example 19
Source File: GetMailMessageService.java From cs-actions with Apache License 2.0 | 4 votes |
protected Map<String, String> getMessageByContentTypes(Message message, String characterSet) throws Exception { Map<String, String> messageMap = new HashMap<>(); if (message.isMimeType(MimeTypes.TEXT_PLAIN)) { messageMap.put(MimeTypes.TEXT_PLAIN, MimeUtility.decodeText(message.getContent().toString())); } else if (message.isMimeType(MimeTypes.TEXT_HTML)) { messageMap.put(MimeTypes.TEXT_HTML, MimeUtility.decodeText(convertMessage(message.getContent().toString()))); } else if (message.isMimeType(MimeTypes.MULTIPART_MIXED) || message.isMimeType(MimeTypes.MULTIPART_RELATED)) { messageMap.put(MimeTypes.MULTIPART_MIXED, extractMultipartMixedMessage(message, characterSet)); } else { Object obj = message.getContent(); Multipart mpart = (Multipart) obj; for (int i = 0, n = mpart.getCount(); i < n; i++) { Part part = mpart.getBodyPart(i); if (input.isEncryptedMessage() && part.getContentType() != null && part.getContentType().equals(SecurityConstants.ENCRYPTED_CONTENT_TYPE)) { part = decryptPart((MimeBodyPart) part); } String disposition = part.getDisposition(); String partContentType = part.getContentType().substring(0, part.getContentType().indexOf(";")); if (disposition == null) { if (part.getContent() instanceof MimeMultipart) { // multipart with attachment MimeMultipart mm = (MimeMultipart) part.getContent(); for (int j = 0; j < mm.getCount(); j++) { if (mm.getBodyPart(j).getContent() instanceof String) { BodyPart bodyPart = mm.getBodyPart(j); if ((characterSet != null) && (characterSet.trim().length() > 0)) { String contentType = bodyPart.getHeader(CONTENT_TYPE)[0]; contentType = contentType .replace(contentType.substring(contentType.indexOf("=") + 1), characterSet); bodyPart.setHeader(CONTENT_TYPE, contentType); } String partContentType1 = bodyPart .getContentType().substring(0, bodyPart.getContentType().indexOf(";")); messageMap.put(partContentType1, MimeUtility.decodeText(bodyPart.getContent().toString())); } } } else { //multipart - w/o attachment //if the user has specified a certain characterSet we decode his way if ((characterSet != null) && (characterSet.trim().length() > 0)) { InputStream istream = part.getInputStream(); ByteArrayInputStream bis = new ByteArrayInputStream(ASCIIUtility.getBytes(istream)); int count = bis.available(); byte[] bytes = new byte[count]; count = bis.read(bytes, 0, count); messageMap.put(partContentType, MimeUtility.decodeText(new String(bytes, 0, count, characterSet))); } else { messageMap.put(partContentType, MimeUtility.decodeText(part.getContent().toString())); } } } } //for } //else return messageMap; }
Example 20
Source File: ParseBlobUploadFilter.java From appengine-java-vm-runtime with Apache License 2.0 | 4 votes |
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; if (req.getHeader(UPLOAD_HEADER) != null) { Map<String, List<String>> blobKeys = new HashMap<String, List<String>>(); Map<String, List<Map<String, String>>> blobInfos = new HashMap<String, List<Map<String, String>>>(); Map<String, List<String>> otherParams = new HashMap<String, List<String>>(); try { MimeMultipart multipart = MultipartMimeUtils.parseMultipartRequest(req); int parts = multipart.getCount(); for (int i = 0; i < parts; i++) { BodyPart part = multipart.getBodyPart(i); String fieldName = MultipartMimeUtils.getFieldName(part); if (part.getFileName() != null) { ContentType contentType = new ContentType(part.getContentType()); if ("message/external-body".equals(contentType.getBaseType())) { String blobKeyString = contentType.getParameter("blob-key"); List<String> keys = blobKeys.get(fieldName); if (keys == null) { keys = new ArrayList<String>(); blobKeys.put(fieldName, keys); } keys.add(blobKeyString); List<Map<String, String>> infos = blobInfos.get(fieldName); if (infos == null) { infos = new ArrayList<Map<String, String>>(); blobInfos.put(fieldName, infos); } infos.add(getInfoFromBody(MultipartMimeUtils.getTextContent(part), blobKeyString)); } } else { List<String> values = otherParams.get(fieldName); if (values == null) { values = new ArrayList<String>(); otherParams.put(fieldName, values); } values.add(MultipartMimeUtils.getTextContent(part)); } } req.setAttribute(UPLOADED_BLOBKEY_ATTR, blobKeys); req.setAttribute(UPLOADED_BLOBINFO_ATTR, blobInfos); } catch (MessagingException ex) { logger.log(Level.WARNING, "Could not parse multipart message:", ex); } chain.doFilter(new ParameterServletWrapper(request, otherParams), response); } else { chain.doFilter(request, response); } }