List of usage examples for javax.mail Multipart getBodyPart
public synchronized BodyPart getBodyPart(int index) throws MessagingException
From source file:org.apache.axis2.transport.mail.SimpleMailListener.java
private void buildSOAPEnvelope(MimeMessage msg, MessageContext msgContext) throws AxisFault { //TODO we assume for the time being that there is only one attachement and this attachement contains the soap evelope try {/*from www . j a va2 s.c om*/ Multipart mp = (Multipart) msg.getContent(); if (mp != null) { for (int i = 0, n = mp.getCount(); i < n; i++) { Part part = mp.getBodyPart(i); String disposition = part.getDisposition(); if (disposition != null && disposition.equalsIgnoreCase(Part.ATTACHMENT)) { String soapAction; /* Set the Charactorset Encoding */ String contentType = part.getContentType(); String charSetEncoding = BuilderUtil.getCharSetEncoding(contentType); if (charSetEncoding != null) { msgContext.setProperty(org.apache.axis2.Constants.Configuration.CHARACTER_SET_ENCODING, charSetEncoding); } else { msgContext.setProperty(org.apache.axis2.Constants.Configuration.CHARACTER_SET_ENCODING, MessageContext.DEFAULT_CHAR_SET_ENCODING); } /* SOAP Action */ soapAction = getMailHeaderFromPart(part, org.apache.axis2.transport.mail.Constants.HEADER_SOAP_ACTION); msgContext.setSoapAction(soapAction); String contentDescription = getMailHeaderFromPart(part, "Content-Description"); /* As an input stream - using the getInputStream() method. Any mail-specific encodings are decoded before this stream is returned.*/ if (contentDescription != null) { msgContext.setTo(new EndpointReference(contentDescription)); } if (contentType.indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) > -1) { TransportUtils.processContentTypeForAction(contentType, msgContext); } else { // According to the mail sepec, mail transport should support only // application/soap+xml; String message = "According to the mail sepec, mail transport " + "should support only application/soap+xml"; log.error(message); throw new AxisFault(message); } String cte = getMailHeaderFromPart(part, "Content-Transfer-Encoding"); if (!(cte != null && cte.equalsIgnoreCase("base64"))) { String message = "Processing of Content-Transfer-Encoding faild."; log.error(message); throw new AxisFault(message); } InputStream inputStream = part.getInputStream(); SOAPEnvelope envelope = TransportUtils.createSOAPMessage(msgContext, inputStream, contentType); msgContext.setEnvelope(envelope); } } } } catch (IOException e) { throw new AxisFault(e.getMessage(), e); } catch (MessagingException e) { throw new AxisFault(e.getMessage(), e); } catch (XMLStreamException e) { throw new AxisFault(e.getMessage(), e); } }
From source file:com.stimulus.archiva.domain.Email.java
protected boolean hasAttachment(Part p) throws MessagingException, IOException { if (p.getDisposition() != null && Compare.equalsIgnoreCase(p.getDisposition(), Part.ATTACHMENT)) { logger.debug("hasAttachment() attachment disposition."); return true; }//from w w w . ja va 2 s .c o m if (p.getFileName() != null) { logger.debug("hasAttachment() filename specified."); return true; } try { if (p.isMimeType("multipart/*")) { Multipart mp = (Multipart) p.getContent(); for (int i = 0; i < mp.getCount(); i++) { logger.debug("hasAttachment() scanning multipart[" + i + "]"); if (hasAttachment(mp.getBodyPart(i))) return true; } } else if (p.isMimeType("message/rfc822")) { return hasAttachment((Part) p.getContent()); } } catch (Exception e) { logger.debug("exception occurred while detecting attachment", e); } return false; }
From source file:org.sakaiproject.kernel.messaging.activemq.ActiveMQEmailDeliveryT.java
private String getBodyAsString(Object content) { Multipart mime = null; StringBuffer sb = new StringBuffer(); if (content instanceof String) { return (String) content; } else if (content instanceof Multipart) { try {/* w w w .j av a2s .c o m*/ mime = (Multipart) content; for (int i = 0; i < mime.getCount(); ++i) { Part p = mime.getBodyPart(i); sb.append(p.getContent()); } } catch (MessagingException e) { e.printStackTrace(); Assert.assertTrue(false); } catch (IOException e) { e.printStackTrace(); Assert.assertTrue(false); } } else { Assert.assertTrue(false); } return sb.toString(); }
From source file:mitm.application.djigzo.relay.RelayHandler.java
private void extractMessageParts(MimeMessage message) throws MessagingException, IOException { /*/*from ww w . ja v a2s. c o m*/ * Fast fail. Only multipart mixed messages are supported. */ if (!message.isMimeType("multipart/mixed")) { return; } Multipart mp; try { mp = (Multipart) message.getContent(); } catch (IOException e) { throw new MessagingException("Error getting message content.", e); } for (int i = 0; i < mp.getCount(); i++) { BodyPart part = mp.getBodyPart(i); if (part.isMimeType("message/rfc822")) { relayMessage = BodyPartUtils.extractFromRFC822(part); } else if (part.isMimeType("text/xml")) { metaPart = part; } if (metaPart != null && relayMessage != null) { break; } } }
From source file:org.alfresco.email.server.impl.subetha.SubethaEmailMessage.java
private void parseMessagePart(Part messagePart) { try {/* www. ja va2s. c om*/ if (messagePart.isMimeType(MIME_PLAIN_TEXT) || messagePart.isMimeType(MIME_HTML_TEXT)) { if (log.isDebugEnabled()) { log.debug("Text or HTML part was found. ContentType: " + messagePart.getContentType()); } addBody(messagePart); } else if (messagePart.isMimeType(MIME_XML_TEXT)) { if (log.isDebugEnabled()) { log.debug("XML part was found."); } addAttachment(messagePart); } else if (messagePart.isMimeType(MIME_APPLICATION)) { if (log.isDebugEnabled()) { log.debug("Application part was found."); } addAttachment(messagePart); } else if (messagePart.isMimeType(MIME_IMAGE)) { if (log.isDebugEnabled()) { log.debug("Image part was found."); } addAttachment(messagePart); } else if (messagePart.isMimeType(MIME_MULTIPART)) { // if multipart, this method will be called recursively // for each of its parts Multipart mp = (Multipart) messagePart.getContent(); int count = mp.getCount(); if (log.isDebugEnabled()) { log.debug("MULTIPART with " + count + " part(s) found. Processin each part..."); } for (int i = 0; i < count; i++) { BodyPart bp = mp.getBodyPart(i); if (bp.getContent() instanceof MimeMultipart) { // It's multipart. Recurse. parseMessagePart(bp); } else { // It's the body addBody(bp); } } if (log.isDebugEnabled()) { log.debug("MULTIPART processed."); } } else if (messagePart.isMimeType(MIME_RFC822)) { // if rfc822, call this method with its content as the part if (log.isDebugEnabled()) { log.debug("MIME_RFC822 part found. Processing inside part..."); } parseMessagePart((Part) messagePart.getContent()); if (log.isDebugEnabled()) { log.debug("MIME_RFC822 processed."); } } else { // if all else fails, put this in the attachments map. // Actually we don't know what it is. if (log.isDebugEnabled()) { log.debug("Unrecognized part was found. Put it into attachments."); } addAttachment(messagePart); } } catch (IOException e) { throw new EmailMessageException(ERR_PARSE_MESSAGE, e.getMessage()); } catch (MessagingException e) { throw new EmailMessageException(ERR_PARSE_MESSAGE, e.getMessage()); } }
From source file:org.alfresco.repo.content.transform.EMLParser.java
/** * Prepare extract multipart./*from w w w . j av a 2 s .co m*/ * * @param xhtml * the xhtml * @param part * the part * @param parentPart * the parent part * @param context * the context * @param attachmentList * is list with attachments to fill * @throws MessagingException * the messaging exception * @throws IOException * Signals that an I/O exception has occurred. * @throws SAXException * the sAX exception * @throws TikaException * the tika exception */ private void prepareExtractMultipart(XHTMLContentHandler xhtml, Part part, Part parentPart, ParseContext context, List<String> attachmentList) throws MessagingException, IOException, SAXException, TikaException { String disposition = part.getDisposition(); if ((disposition != null && disposition.contains(Part.ATTACHMENT))) { String fileName = part.getFileName(); if (fileName != null && fileName.startsWith("=?")) { fileName = MimeUtility.decodeText(fileName); } attachmentList.add(fileName); } String[] header = part.getHeader("Content-ID"); String key = null; if (header != null) { for (String string : header) { key = string; } } if (part.isMimeType("multipart/*")) { Multipart mp = (Multipart) part.getContent(); int count = mp.getCount(); for (int i = 0; i < count; i++) { prepareExtractMultipart(xhtml, mp.getBodyPart(i), part, context, attachmentList); } } else if (part.isMimeType(MimetypeMap.MIMETYPE_RFC822)) { prepareExtractMultipart(xhtml, (Part) part.getContent(), part, context, attachmentList); } else { if (key == null) { return; } // if ((disposition != null && disposition.contains(Part.INLINE))) { InputStream stream = part.getInputStream(); File file = new File(workingDirectory, System.currentTimeMillis() + ""); FileOutputStream fileOutputStream = new FileOutputStream(file); IOUtils.copy(stream, fileOutputStream); IOUtils.closeQuietly(fileOutputStream); String src = file.getName(); String replace = key.replace("<", "").replace(">", ""); referencesCache.put(replace, src); // } } }
From source file:org.accesointeligente.server.robots.ResponseChecker.java
public void connectAndCheck() { if (ApplicationProperties.getProperty("email.server") == null || ApplicationProperties.getProperty("email.user") == null || ApplicationProperties.getProperty("email.password") == null || ApplicationProperties.getProperty("email.folder") == null || ApplicationProperties.getProperty("email.failfolder") == null || ApplicationProperties.getProperty("attachment.directory") == null || ApplicationProperties.getProperty("attachment.baseurl") == null) { logger.error("Properties are not defined!"); return;/*from w w w. j a va 2 s .c om*/ } org.hibernate.Session hibernate = null; try { session = Session.getInstance(props, null); store = session.getStore("imaps"); store.connect(ApplicationProperties.getProperty("email.server"), ApplicationProperties.getProperty("email.user"), ApplicationProperties.getProperty("email.password")); Folder failbox = store.getFolder(ApplicationProperties.getProperty("email.failfolder")); Folder inbox = store.getFolder(ApplicationProperties.getProperty("email.folder")); inbox.open(Folder.READ_WRITE); for (Message message : inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false))) { try { logger.info("Sender: " + message.getFrom()[0] + "\tSubject: " + message.getSubject()); remoteIdentifiers = null; messageBody = null; remoteIdentifiers = new HashSet<String>(); if (message.getSubject() != null) { Matcher matcher = pattern.matcher(message.getSubject()); if (matcher.matches()) { remoteIdentifiers.add(formatIdentifier(matcher.group(1), matcher.group(2), Integer.parseInt(matcher.group(3)))); logger.info("remote identifier: " + formatIdentifier(matcher.group(1), matcher.group(2), Integer.parseInt(matcher.group(3)))); } } Object content = message.getContent(); if (content instanceof Multipart) { Multipart mp = (Multipart) message.getContent(); logger.info("Email content type is Multipart, each part of " + mp.getCount() + " will be processed"); for (int i = 0, n = mp.getCount(); i < n; i++) { Part part = mp.getBodyPart(i); logger.info("Part: " + (i + 1) + " of " + mp.getCount()); processPart(part); } } else if (content instanceof String) { logger.info("Email content type is String"); messageBody = (String) content; Matcher matcher; StringTokenizer tokenizer = new StringTokenizer(messageBody); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); matcher = pattern.matcher(token); if (matcher.matches()) { remoteIdentifiers.add(formatIdentifier(matcher.group(1), matcher.group(2), Integer.parseInt(matcher.group(3)))); logger.info("remote identifier: " + formatIdentifier(matcher.group(1), matcher.group(2), Integer.parseInt(matcher.group(3)))); } } } else { logger.info("Email content type isn't String or Multipart"); message.setFlag(Flag.SEEN, false); inbox.copyMessages(new Message[] { message }, failbox); message.setFlag(Flag.DELETED, true); inbox.expunge(); continue; } Boolean requestFound = false; Matcher matcher = htmlPattern.matcher(messageBody); if (matcher.find()) { messageBody = htmlToString(messageBody); } logger.info("Searching for Request Remote Identifier"); for (String remoteIdentifier : remoteIdentifiers) { hibernate = HibernateUtil.getSession(); hibernate.beginTransaction(); Criteria criteria = hibernate.createCriteria(Request.class); criteria.add(Restrictions.eq("remoteIdentifier", remoteIdentifier)); Request request = (Request) criteria.uniqueResult(); hibernate.getTransaction().commit(); if (request != null) { logger.info("Request found for Remote Identifier: " + remoteIdentifier); Response response; // If the attachments haven't been used, use them. Otherwise, copy them. if (!requestFound) { response = createResponse(message.getFrom()[0].toString(), message.getSentDate(), message.getSubject(), messageBody); } else { response = createResponse(message.getFrom()[0].toString(), message.getSentDate(), message.getSubject(), messageBody); } hibernate = HibernateUtil.getSession(); hibernate.beginTransaction(); response.setRequest(request); request.setStatus(RequestStatus.RESPONDED); request.setExpired(RequestExpireType.WITHRESPONSE); request.setResponseDate(new Date()); hibernate.update(request); hibernate.update(response); hibernate.getTransaction().commit(); requestFound = true; } } if (!requestFound) { logger.info("Request not found"); createResponse(message.getFrom()[0].toString(), message.getSentDate(), message.getSubject(), messageBody); message.setFlag(Flag.SEEN, false); inbox.copyMessages(new Message[] { message }, failbox); message.setFlag(Flag.DELETED, true); inbox.expunge(); } } catch (Exception e) { if (hibernate != null && hibernate.isOpen() && hibernate.getTransaction().isActive()) { hibernate.getTransaction().rollback(); } logger.error(e.getMessage(), e); } } } catch (Exception e) { if (hibernate != null && hibernate.isOpen() && hibernate.getTransaction().isActive()) { hibernate.getTransaction().rollback(); } logger.error(e.getMessage(), e); } }
From source file:de.kp.ames.web.function.access.imap.ImapConsumer.java
/** * @param mp//from w w w. j av a 2 s . c o m * @param attach * @return * @throws Exception */ private FileUtil handleMultipart(Multipart mp, boolean attach) throws Exception { FileUtil file = null; for (int i = 0; i < mp.getCount(); i++) { file = handlePart(mp.getBodyPart(i), attach); } return file; }
From source file:de.kp.ames.web.function.access.imap.ImapConsumer.java
/** * @param mp// w ww . jav a 2 s .c o m * @return * @throws Exception */ private String messageFromMultipart(Multipart mp) throws Exception { String message = ""; int count = mp.getCount(); for (int i = 0; i < count; i++) { Part part = mp.getBodyPart(i); String text = messageFromPart(part); if (!text.equals("")) message = text; } return message; }
From source file:org.apache.solr.handler.dataimport.FsMailEntityProcessor.java
public boolean addPartToDocument(Part part, Map<String, Object> row, boolean outerMost) throws Exception { if (outerMost && part instanceof Message) { if (!addEnvelopToDocument(part, row)) { return false; }// www. ja v a 2 s . c o m // store hash row.put(HASH, DigestUtils.md5Hex((String) row.get(FROM_CLEAN) + "" + (String) row.get(SUBJECT))); } String ct = part.getContentType(); ContentType ctype = new ContentType(ct); if (part.isMimeType("multipart/*")) { Multipart mp = (Multipart) part.getContent(); int count = mp.getCount(); if (part.isMimeType("multipart/alternative")) { count = 1; } for (int i = 0; i < count; i++) { addPartToDocument(mp.getBodyPart(i), row, false); } } else if (part.isMimeType("message/rfc822")) { addPartToDocument((Part) part.getContent(), row, false); } else { String disp = part.getDisposition(); @SuppressWarnings("resource") // Tika will close stream InputStream is = part.getInputStream(); String fileName = part.getFileName(); Metadata md = new Metadata(); md.set(HttpHeaders.CONTENT_TYPE, ctype.getBaseType().toLowerCase(Locale.ROOT)); md.set(TikaMetadataKeys.RESOURCE_NAME_KEY, fileName); String content = this.tika.parseToString(is, md); if (disp != null && disp.equalsIgnoreCase(Part.ATTACHMENT)) { if (row.get(ATTACHMENT) == null) { row.put(ATTACHMENT, new ArrayList<String>()); } List<String> contents = (List<String>) row.get(ATTACHMENT); contents.add(content); row.put(ATTACHMENT, contents); if (row.get(ATTACHMENT_NAMES) == null) { row.put(ATTACHMENT_NAMES, new ArrayList<String>()); } List<String> names = (List<String>) row.get(ATTACHMENT_NAMES); names.add(fileName); row.put(ATTACHMENT_NAMES, names); } else { if (row.get(CONTENT) == null) { row.put(CONTENT, new ArrayList<String>()); } List<String> contents = (List<String>) row.get(CONTENT); contents.add(content); row.put(CONTENT, contents); } } return true; }