List of usage examples for javax.mail BodyPart getContentType
public String getContentType() throws MessagingException;
From source file:net.fenyo.mail4hotspot.service.MailManager.java
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; }/*from w ww.j a v a 2s . co m*/ 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 slectionne la premire part non vide - ce n'est pas forcment la meilleure alternative, mais comment diffrentiel un text/plain d'une pice jointe d'un text/plain du corps du message, accompagnant un text/html du mme 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(); }
From source file:com.zimbra.cs.mailbox.calendar.Invite.java
/** * Returns the meeting notes. Meeting notes is the text/plain part in an * invite. It typically includes CUA-generated meeting summary as well as * text entered by the user.//from w w w. j a v a2s .co m * * @return null if notes is not found * @throws ServiceException */ public static String getDescription(Part mmInv, String mimeType) throws ServiceException { if (mmInv == null) return null; try { // If top-level is text/calendar, parse the iCalendar object and return // the DESCRIPTION of the first VEVENT/VTODO encountered. String mmCtStr = mmInv.getContentType(); if (mmCtStr != null) { ContentType mmCt = new ContentType(mmCtStr); if (mmCt.match(MimeConstants.CT_TEXT_CALENDAR)) { boolean wantHtml = MimeConstants.CT_TEXT_HTML.equalsIgnoreCase(mimeType); Object mmInvContent = mmInv.getContent(); InputStream is = null; try { String charset = MimeConstants.P_CHARSET_UTF8; if (mmInvContent instanceof InputStream) { charset = mmCt.getParameter(MimeConstants.P_CHARSET); if (charset == null) charset = MimeConstants.P_CHARSET_UTF8; is = (InputStream) mmInvContent; } else if (mmInvContent instanceof String) { String str = (String) mmInvContent; charset = MimeConstants.P_CHARSET_UTF8; is = new ByteArrayInputStream(str.getBytes(charset)); } if (is != null) { ZVCalendar iCal = ZCalendarBuilder.build(is, charset); for (Iterator<ZComponent> compIter = iCal.getComponentIterator(); compIter.hasNext();) { ZComponent component = compIter.next(); ICalTok compTypeTok = component.getTok(); if (compTypeTok == ICalTok.VEVENT || compTypeTok == ICalTok.VTODO) { if (!wantHtml) return component.getPropVal(ICalTok.DESCRIPTION, null); else return component.getDescriptionHtml(); } } } } finally { ByteUtil.closeStream(is); } } } Object mmInvContent = mmInv.getContent(); if (!(mmInvContent instanceof MimeMultipart)) { if (mmInvContent instanceof InputStream) { ByteUtil.closeStream((InputStream) mmInvContent); } return null; } MimeMultipart mm = (MimeMultipart) mmInvContent; // If top-level is multipart, get description from text/* part. int numParts = mm.getCount(); String charset = null; for (int i = 0; i < numParts; i++) { BodyPart part = mm.getBodyPart(i); String ctStr = part.getContentType(); try { ContentType ct = new ContentType(ctStr); if (ct.match(mimeType)) { charset = ct.getParameter(MimeConstants.P_CHARSET); if (charset == null) charset = MimeConstants.P_CHARSET_DEFAULT; byte[] descBytes = ByteUtil.getContent(part.getInputStream(), part.getSize()); return new String(descBytes, charset); } // If part is a multipart, recurse. if (ct.getBaseType().matches(MimeConstants.CT_MULTIPART_WILD)) { String str = getDescription(part, mimeType); if (str != null) { return str; } } } catch (javax.mail.internet.ParseException e) { ZimbraLog.calendar.warn("Invalid Content-Type found: \"" + ctStr + "\"; skipping part", e); } } } catch (IOException e) { throw ServiceException.FAILURE("Unable to get calendar item notes MIME part", e); } catch (MessagingException e) { throw ServiceException.FAILURE("Unable to get calendar item notes MIME part", e); } return null; }
From source file:nl.nn.adapterframework.http.HttpSender.java
public static String handleMultipartResponse(String contentType, InputStream inputStream, ParameterResolutionContext prc, HttpMethod httpMethod) throws IOException, SenderException { String result = null;// www . ja v a 2 s . c om try { InputStreamDataSource dataSource = new InputStreamDataSource(contentType, 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 = org.apache.http.entity.ContentType.parse(bodyPart.getContentType()) .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. prc.getSession().put("multipart" + i, new ReleaseConnectionAfterReadInputStream( lastPart ? httpMethod : null, bodyPart.getInputStream())); } } } catch (MessagingException e) { throw new SenderException("Could not read mime multipart response", e); } return result; }
From source file:org.alfresco.cacheserver.CacheServer.java
public List<Patch> getPatches(String host, int port, String nodeId, long nodeVersion) throws MessagingException, IOException { List<Patch> patches = new LinkedList<>(); StringBuilder sb = new StringBuilder(); sb.append("/patch/"); sb.append(nodeId);//from w ww . j av a 2 s . co m sb.append("/"); sb.append(nodeVersion); String url = sb.toString(); final ClientConfig config = new DefaultClientConfig(); config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); final Client client = Client.create(config); final WebResource resource = client.resource(url); final MimeMultipart response = resource.get(MimeMultipart.class); // This will iterate the individual parts of the multipart response for (int i = 0; i < response.getCount(); i++) { final BodyPart part = response.getBodyPart(i); System.out.printf("Embedded Body Part [Mime Type: %s, Length: %s]\n", part.getContentType(), part.getSize()); InputStream in = part.getInputStream(); // Patch patch = new Patch(); // patches.add(patch); } return patches; }
From source file:org.apache.camel.component.mail.MailBinding.java
protected void addAttachmentsToMultipart(MimeMultipart multipart, String partDisposition, Exchange exchange) throws MessagingException { LOG.trace("Adding attachments +++ start +++"); int i = 0;/* ww w .j a v a 2s. co m*/ for (Map.Entry<String, DataHandler> entry : exchange.getIn().getAttachments().entrySet()) { String attachmentFilename = entry.getKey(); DataHandler handler = entry.getValue(); if (LOG.isTraceEnabled()) { LOG.trace("Attachment #" + i + ": Disposition: " + partDisposition); LOG.trace("Attachment #" + i + ": DataHandler: " + handler); LOG.trace("Attachment #" + i + ": FileName: " + attachmentFilename); } if (handler != null) { if (shouldAddAttachment(exchange, attachmentFilename, handler)) { // Create another body part BodyPart messageBodyPart = new MimeBodyPart(); // Set the data handler to the attachment messageBodyPart.setDataHandler(handler); if (attachmentFilename.toLowerCase().startsWith("cid:")) { // add a Content-ID header to the attachment // must use angle brackets according to RFC: http://www.ietf.org/rfc/rfc2392.txt messageBodyPart.addHeader("Content-ID", "<" + attachmentFilename.substring(4) + ">"); // Set the filename without the cid messageBodyPart.setFileName(attachmentFilename.substring(4)); } else { // Set the filename messageBodyPart.setFileName(attachmentFilename); } LOG.trace("Attachment #" + i + ": ContentType: " + messageBodyPart.getContentType()); if (contentTypeResolver != null) { String contentType = contentTypeResolver.resolveContentType(attachmentFilename); LOG.trace("Attachment #" + i + ": Using content type resolver: " + contentTypeResolver + " resolved content type as: " + contentType); if (contentType != null) { String value = contentType + "; name=" + attachmentFilename; messageBodyPart.setHeader("Content-Type", value); LOG.trace("Attachment #" + i + ": ContentType: " + messageBodyPart.getContentType()); } } // Set Disposition messageBodyPart.setDisposition(partDisposition); // Add part to multipart multipart.addBodyPart(messageBodyPart); } else { LOG.trace("shouldAddAttachment: false"); } } else { LOG.warn("Cannot add attachment: " + attachmentFilename + " as DataHandler is null"); } i++; } LOG.trace("Adding attachments +++ done +++"); }
From source file:org.apache.hupa.server.preferences.InImapUserPreferencesStorage.java
/** * Opens the IMAP folder and read messages until it founds the magic subject, * then gets the attachment which contains the data and return the serialized object stored. */// www . j a v a 2 s .c o m protected static Object readUserPreferencesFromIMAP(Log logger, User user, IMAPStore iStore, String folderName, String magicType) throws MessagingException, IOException, ClassNotFoundException { Folder folder = iStore.getFolder(folderName); if (folder.exists()) { if (!folder.isOpen()) { folder.open(Folder.READ_WRITE); } Message message = null; Message[] msgs = folder.getMessages(); for (Message msg : msgs) { if (magicType.equals(msg.getSubject())) { message = msg; break; } } if (message != null) { Object con = message.getContent(); if (con instanceof Multipart) { Multipart mp = (Multipart) con; for (int i = 0; i < mp.getCount(); i++) { BodyPart part = mp.getBodyPart(i); if (part.getContentType().toLowerCase().startsWith(HUPA_DATA_MIME_TYPE)) { ObjectInputStream ois = new ObjectInputStream(part.getInputStream()); Object o = ois.readObject(); ois.close(); logger.info("Returning user preferences of type " + magicType + " from imap folder + " + folderName + " for user " + user); return o; } } } } } return null; }
From source file:org.apache.hupa.server.utils.MessageUtils.java
static public List<BodyPart> extractInlineImages(Log logger, Object content) throws MessagingException, IOException { ArrayList<BodyPart> ret = new ArrayList<BodyPart>(); for (BodyPart attach : extractMessageAttachments(logger, content)) { if (attach.getHeader("Content-ID") != null && attach.getContentType().startsWith("image/")) ret.add(attach);//from w w w .ja va2 s .c o m } return ret; }
From source file:org.apache.james.postage.mail.MailMatchingUtils.java
public static int getMimePartSize(MimeMultipart parts, String mimeType) { if (parts != null) { try {/*w w w . ja v a 2 s . c o m*/ for (int i = 0; i < parts.getCount(); i++) { BodyPart bodyPart = parts.getBodyPart(i); if (bodyPart.getContentType().startsWith(mimeType)) { try { Object content = bodyPart.getContent(); if (content instanceof InputStream) { ByteArrayOutputStream os = new ByteArrayOutputStream(); IOUtils.copy(((InputStream) content), os); return os.size(); } else if (content instanceof String) { return ((String) content).length(); } else { throw new IllegalStateException( "Unsupported content: " + content.getClass().toString()); } } catch (IOException e) { throw new IllegalStateException("Unexpected IOException in getContent()"); } } } } catch (MessagingException e) { log.info("failed to process body parts.", e); } } return 0; }
From source file:org.apache.james.transport.mailets.DSNBounceTest.java
@Test public void serviceShouldSendMultipartMailContainingTextPart() throws Exception { FakeMailetConfig mailetConfig = FakeMailetConfig.builder().mailetName(MAILET_NAME) .mailetContext(fakeMailContext).build(); dsnBounce.init(mailetConfig);/*w w w .j ava 2 s.co m*/ MailAddress senderMailAddress = new MailAddress("sender@domain.com"); FakeMail mail = FakeMail.builder().sender(senderMailAddress).attribute("delivery-error", "Delivery error") .mimeMessage(MimeMessageBuilder.mimeMessageBuilder().setText("My content")).name(MAILET_NAME) .recipient("recipient@domain.com").lastUpdated(Date.from(Instant.parse("2016-09-08T14:25:52.000Z"))) .build(); dsnBounce.service(mail); String hostname = InetAddress.getLocalHost().getHostName(); String expectedContent = "Hi. This is the James mail server at " + hostname + ".\nI'm afraid I wasn't able to deliver your message to the following addresses.\nThis is a permanent error; I've given up. Sorry it didn't work out. Below\nI include the list of recipients and the reason why I was unable to deliver\nyour message.\n\n" + "Failed recipient(s):\n" + "recipient@domain.com\n" + "\n" + "Error message:\n" + "Delivery error\n" + "\n"; List<SentMail> sentMails = fakeMailContext.getSentMails(); assertThat(sentMails).hasSize(1); SentMail sentMail = sentMails.get(0); MimeMessage sentMessage = sentMail.getMsg(); MimeMultipart content = (MimeMultipart) sentMessage.getContent(); BodyPart bodyPart = content.getBodyPart(0); assertThat(bodyPart.getContentType()).isEqualTo("text/plain; charset=us-ascii"); assertThat(bodyPart.getContent()).isEqualTo(expectedContent); }