List of usage examples for javax.mail Multipart getBodyPart
public synchronized BodyPart getBodyPart(int index) throws MessagingException
From source file:org.apache.hupa.server.handler.GetMessageDetailsHandler.java
private boolean handleMultiPartAlternative(Multipart mp, StringBuffer sbPlain) throws MessagingException, IOException { String text = null;/* w w w .ja va2 s.c o m*/ boolean isHTML = false; for (int i = 0; i < mp.getCount(); i++) { Part part = mp.getBodyPart(i); String contentType = part.getContentType().toLowerCase(); // we prefer html if (text == null && contentType.startsWith("text/plain")) { isHTML = false; text = (String) part.getContent(); } else if (contentType.startsWith("text/html")) { isHTML = true; text = (String) part.getContent(); } } sbPlain.append(text); return isHTML; }
From source file:ru.retbansk.utils.scheduled.impl.ReadEmailAndConvertToXmlSpringImpl.java
/** * Loads email properties, reads email messages, * converts their multipart bodies into string, * send error emails if message doesn't contain valid report and at last returns a reversed Set of the Valid Reports * <p><b> deletes messages/*from w ww . ja va 2 s. c om*/ * @see #readEmail() * @see #convertToXml(HashSet) * @see ru.retbansk.utils.scheduled.ReplyManager * @return HashSet<DayReport> of the Valid Day Reports */ @Override public HashSet<DayReport> readEmail() throws Exception { Properties prop = loadProperties(); String host = prop.getProperty("host"); String user = prop.getProperty("user"); String password = prop.getProperty("password"); path = prop.getProperty("path"); // Get system properties Properties properties = System.getProperties(); // Get the default Session object. Session session = Session.getDefaultInstance(properties); // Get a Store object that implements the specified protocol. Store store = session.getStore("pop3"); // Connect to the current host using the specified username and // password. store.connect(host, user, password); // Create a Folder object corresponding to the given name. Folder folder = store.getFolder("inbox"); // Open the Folder. folder.open(Folder.READ_WRITE); HashSet<DayReport> dayReportSet = new HashSet<DayReport>(); try { // Getting messages from the folder Message[] message = folder.getMessages(); // Reversing the order in the array with the use of Set to make the last one final Collections.reverse(Arrays.asList(message)); // Reading messages. String body; for (int i = 0; i < message.length; i++) { DayReport dayReport = null; dayReport = new DayReport(); dayReport.setPersonId(((InternetAddress) message[i].getFrom()[0]).getAddress()); Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+3")); calendar.setTime(message[i].getSentDate()); dayReport.setCalendar(calendar); dayReport.setSubject(message[i].getSubject()); List<TaskReport> reportList = null; //Release the string from email message body body = ""; Object content = message[i].getContent(); if (content instanceof java.lang.String) { body = (String) content; } else if (content instanceof Multipart) { Multipart mp = (Multipart) content; for (int j = 0; j < mp.getCount(); j++) { Part part = mp.getBodyPart(j); String disposition = part.getDisposition(); if (disposition == null) { MimeBodyPart mbp = (MimeBodyPart) part; if (mbp.isMimeType("text/plain")) { body += (String) mbp.getContent(); } } else if ((disposition != null) && (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE))) { MimeBodyPart mbp = (MimeBodyPart) part; if (mbp.isMimeType("text/plain")) { body += (String) mbp.getContent(); } } } } //Put the string (body of email message) and get list of valid reports else send error reportList = new ArrayList<TaskReport>(); reportList = giveValidReports(body, message[i].getSentDate()); //Check for valid day report. To be valid it should have size of reportList > 0. if (reportList.size() > 0) { // adding valid ones to Set dayReport.setReportList(reportList); dayReportSet.add(dayReport); } else { // This message doesn't have valid reports. Sending an error reply. logger.info("Invalid Day Report detected. Sending an error reply"); ReplyManager man = new ReplyManagerSimpleImpl(); man.sendError(dayReport); } // Delete message message[i].setFlag(Flags.Flag.DELETED, true); } } finally { // true tells the mail server to expunge deleted messages. folder.close(true); store.close(); } return dayReportSet; }
From source file:org.apache.oozie.action.email.TestEmailActionExecutor.java
private void assertAttachment(String attachtag, int attachCount, String content1, String content2) throws Exception { sendAndReceiveEmail(attachtag);/*from w w w. j a v a 2s . co m*/ MimeMessage retMeg = server.getReceivedMessages()[0]; Multipart retParts = (Multipart) (retMeg.getContent()); int numAttach = 0; for (int i = 0; i < retParts.getCount(); i++) { BodyPart bp = retParts.getBodyPart(i); String disp = bp.getDisposition(); String retValue = IOUtils.toString(bp.getInputStream()); if (disp != null && (disp.equals(BodyPart.ATTACHMENT))) { assertTrue(retValue.equals(content1) || retValue.equals(content2)); numAttach++; } else { assertEquals("This is a test mail", retValue); } } assertEquals(attachCount, numAttach); }
From source file:gov.nih.nci.cacis.nav.DefaultNotificationValidator.java
private void validateMultiparts(Multipart multipart) throws NotificationValidationException { try {/*w ww. j av a 2s . co m*/ if (multipart.getCount() != 2) { throw new NotificationValidationException(ERR_RQR_2_PRTS_MSG); } validateTextBodyPart(multipart.getBodyPart(0)); validateAttachmentBodyPart(multipart.getBodyPart(1)); } catch (MessagingException e) { throw new NotificationValidationException(ERR_INVALID_MULTIPART_MSG, e); } }
From source file:org.webguitoolkit.messagebox.mail.MailChannel.java
/** * Drag the content from the message into a String * //from w ww . j a va 2 s . c om * @param m * @return */ private String getContent(Message m) { try { Object content = m.getContent(); if (content instanceof String) { return (String) content; } else if (content instanceof Multipart) { Multipart multipart = (Multipart) content; int partCount = multipart.getCount(); StringBuffer result = new StringBuffer(); for (int j = 0; j < partCount; j++) { BodyPart bodyPart = multipart.getBodyPart(j); String mimeType = bodyPart.getContentType(); Object partContent = bodyPart.getContent(); if (partContent instanceof String) { result.append((String) partContent); } else if (partContent instanceof Multipart) { Multipart innerMultiPartContent = (Multipart) partContent; int innerPartCount = innerMultiPartContent.getCount(); result.append("*** It has " + innerPartCount + "further BodyParts in it ***"); } else if (partContent instanceof InputStream) { result.append(IOUtils.toString((InputStream) partContent)); } } // End of for return result.toString(); } else if (content instanceof InputStream) return IOUtils.toString((InputStream) content); } catch (Exception e) { return "ERROR reading mail content " + e.getMessage(); } return "ERROR reading mail content - unknown format"; }
From source file:com.consol.citrus.mail.message.MailMessageConverter.java
/** * Construct multipart body with first part being the body content and further parts being the attachments. * @param body// w w w.j a v a 2 s . c o m * @return * @throws IOException */ private BodyPart handleMultiPart(Multipart body) throws IOException, MessagingException { BodyPart bodyPart = null; for (int i = 0; i < body.getCount(); i++) { MimePart entity = (MimePart) body.getBodyPart(i); if (bodyPart == null) { bodyPart = handlePart(entity); } else { BodyPart attachment = handlePart(entity); bodyPart.addPart(new AttachmentPart(attachment.getContent(), parseContentType(attachment.getContentType()), entity.getFileName())); } } return bodyPart; }
From source file:ch.entwine.weblounge.bridge.mail.MailAggregator.java
/** * Aggregates the e-mail message by reading it and turning it either into a * page or a file upload./*from w w w . j av a 2 s. c o m*/ * * @param message * the e-mail message * @param site * the site to publish to * @throws MessagingException * if fetching the message data fails * @throws IOException * if writing the contents to the output stream fails */ protected Page aggregate(Message message, Site site) throws IOException, MessagingException, IllegalArgumentException { ResourceURI uri = new PageURIImpl(site, UUID.randomUUID().toString()); Page page = new PageImpl(uri); Language language = site.getDefaultLanguage(); // Extract title and subject. Without these two, creating a page is not // feasible, therefore both messages throw an IllegalArgumentException if // the fields are not present. String title = getSubject(message); String author = getAuthor(message); // Collect default settings PageTemplate template = site.getDefaultTemplate(); if (template == null) throw new IllegalStateException("Missing default template in site '" + site + "'"); String stage = template.getStage(); if (StringUtils.isBlank(stage)) throw new IllegalStateException( "Missing stage definition in template '" + template.getIdentifier() + "'"); // Standard fields page.setTitle(title, language); page.setTemplate(template.getIdentifier()); page.setPublished(new UserImpl(site.getAdministrator()), message.getReceivedDate(), null); // TODO: Translate e-mail "from" into site user and throw if no such // user can be found page.setCreated(site.getAdministrator(), message.getSentDate()); // Start looking at the message body String contentType = message.getContentType(); if (StringUtils.isBlank(contentType)) throw new IllegalArgumentException("Message content type is unspecified"); // Text body if (contentType.startsWith("text/plain")) { // TODO: Evaluate charset String body = null; if (message.getContent() instanceof String) body = (String) message.getContent(); else if (message.getContent() instanceof InputStream) body = IOUtils.toString((InputStream) message.getContent()); else throw new IllegalArgumentException("Message body is of unknown type"); return handleTextPlain(body, page, language); } // HTML body if (contentType.startsWith("text/html")) { // TODO: Evaluate charset return handleTextHtml((String) message.getContent(), page, null); } // Multipart body else if ("mime/multipart".equalsIgnoreCase(contentType)) { Multipart mp = (Multipart) message.getContent(); for (int i = 0, n = mp.getCount(); i < n; i++) { Part part = mp.getBodyPart(i); String disposition = part.getDisposition(); if (disposition == null) { MimeBodyPart mbp = (MimeBodyPart) part; if (mbp.isMimeType("text/plain")) { return handleTextPlain((String) mbp.getContent(), page, null); } else { // TODO: Implement special non-attachment cases here of // image/gif, text/html, ... throw new UnsupportedOperationException("Multipart message bodies of type '" + mbp.getContentType() + "' are not yet supported"); } } else if (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE)) { logger.info("Skipping message attachment " + part.getFileName()); // saveFile(part.getFileName(), part.getInputStream()); } } throw new IllegalArgumentException("Multipart message did not contain any recognizable content"); } // ? else { throw new IllegalArgumentException("Message body is of unknown type '" + contentType + "'"); } }
From source file:com.glaf.mail.business.MailBean.java
/** * ?/*from w ww.ja v a 2 s.c om*/ * * @param part * @throws MessagingException * @throws IOException */ public void parseAttachment(Part part) throws MessagingException, IOException { String filename = ""; if (part.isMimeType("multipart/*")) { Multipart mp = (Multipart) part.getContent(); for (int i = 0; i < mp.getCount(); i++) { BodyPart mpart = mp.getBodyPart(i); String dispostion = mpart.getDisposition(); if ((dispostion != null) && (dispostion.equals(Part.ATTACHMENT) || dispostion.equals(Part.INLINE))) { filename = mpart.getFileName(); if (filename != null) { logger.debug("orig filename=" + filename); if (filename.indexOf("?") != -1) { filename = new String(filename.getBytes("GBK"), "UTF-8"); } if (filename.toLowerCase().indexOf("gb2312") != -1) { filename = MimeUtility.decodeText(filename); } filename = MailUtils.convertString(filename); logger.debug("filename=" + filename); parseFileContent(filename, mpart.getInputStream()); } } else if (mpart.isMimeType("multipart/*")) { parseAttachment(mpart); } else { filename = mpart.getFileName(); if (filename != null) { logger.debug("orig filename=" + filename); if (filename.indexOf("?") != -1) { filename = new String(filename.getBytes("GBK"), "UTF-8"); } if (filename.toLowerCase().indexOf("gb2312") != -1) { filename = MimeUtility.decodeText(filename); } filename = MailUtils.convertString(filename); parseFileContent(filename, mpart.getInputStream()); logger.debug("filename=" + filename); } } } } else if (part.isMimeType("message/rfc822")) { parseAttachment((Part) part.getContent()); } }
From source file:com.riq.MailHandlerServlet.java
private String getText(Part p) throws MessagingException, IOException { // log.info("Message S Zero"); // log.info("Inside MailServlet getText"); if (p.isMimeType("text/*")) { String s = (String) p.getContent(); log.info("Message S1: " + s); boolean textIsHtml = p.isMimeType("text/html"); return s; }//from w w w . ja va2 s . co m if (p.isMimeType("multipart/alternative")) { Multipart mp = (Multipart) p.getContent(); String text = null; for (int i = 0; i < mp.getCount(); i++) { Part bp = mp.getBodyPart(i); if (bp.isMimeType("text/plain")) { if (text == null) text = getText(bp); log.info("Message S2: " + text); continue; } else if (bp.isMimeType("text/html")) { String s = getText(bp); if (s != null) log.info("Message S3: " + s); return s; } else if (bp.isMimeType("message/rfc822")) { Object nestedObject = ""; nestedObject = bp.getContent(); Multipart nestedPart = (Multipart) nestedObject; BodyPart nestedBodyPart = nestedPart.getBodyPart(0); String s = getText(nestedBodyPart); if (s != null) log.info("Message Nested: " + s); return s; } else { log.info("Message nada"); return getText(bp); } } return text; } else if (p.isMimeType("multipart/*")) { Multipart mp = (Multipart) p.getContent(); for (int i = 0; i < mp.getCount(); i++) { String s = getText(mp.getBodyPart(i)); if (s != null) { log.info("Message S4: " + s); return s; } } } return null; }
From source file:com.canoo.webtest.plugins.emailtest.EmailMessageStructureFilter.java
private void filterMultiPartMessage(final Object content, final Message message) throws MessagingException { final Multipart parts = (Multipart) content; final StringBuffer buf = new StringBuffer(); buf.append("<message type=\"MIME\" contentType=\""); buf.append(extractBaseContentType(message.getContentType())).append("\">").append(LS); processHeaders(buf, message);//w w w . j av a 2 s.c o m int count = parts.getCount(); for (int i = 0; i < count; i++) { buf.append(processMessagePart(parts.getBodyPart(i))); } buf.append("</message>"); defineAsCurrentResponse(buf.toString().getBytes(), "text/xml"); }