List of usage examples for javax.mail.internet MimeMultipart getCount
@Override public synchronized int getCount() throws MessagingException
From source file:mitm.application.djigzo.james.mailets.BlackberrySMIMEAdapterTest.java
@Test public void testInvalidEncoding() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); SendMailEventListenerImpl listener = new SendMailEventListenerImpl(); mailetConfig.getMailetContext().setSendMailEventListener(listener); Mailet mailet = new BlackberrySMIMEAdapter(); String template = FileUtils.readFileToString( new File("test/resources/templates/blackberry-smime-adapter-invalid-encoding.ftl")); autoTransactDelegator.setProperty("test@EXAMPLE.com", "pdfTemplate", template); mailetConfig.setInitParameter("log", "starting"); /* use some dummy template because we must specify the default template */ mailetConfig.setInitParameter("template", "sms.ftl"); mailetConfig.setInitParameter("templateProperty", "pdfTemplate"); mailet.init(mailetConfig);//from ww w .java 2s . co m MockMail mail = new MockMail(); mail.setState(Mail.DEFAULT); MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/signed-opaque-validcertificate.eml")); mail.setMessage(message); Collection<MailAddress> recipients = new LinkedList<MailAddress>(); recipients.add(new MailAddress("123@EXAMPLE.com")); mail.setRecipients(recipients); mail.setSender(new MailAddress("sender@example.com")); mailet.service(mail); MailUtils.validateMessage(mail.getMessage()); assertTrue(mail.getMessage().isMimeType("multipart/mixed")); assertFalse(mail.getMessage() == message); MimeMultipart mp = (MimeMultipart) mail.getMessage().getContent(); assertEquals(2, mp.getCount()); BodyPart bp = mp.getBodyPart(0); assertTrue(bp.isMimeType("text/plain")); bp = mp.getBodyPart(1); assertTrue(bp.isMimeType("application/octet-stream")); assertEquals("x-rimdevicesmime.p7m", bp.getFileName()); }
From source file:mitm.application.djigzo.james.mailets.BlackberrySMIMEAdapterTest.java
@Test public void testSMIMEAdaptMessage() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); SendMailEventListenerImpl listener = new SendMailEventListenerImpl(); mailetConfig.getMailetContext().setSendMailEventListener(listener); Mailet mailet = new BlackberrySMIMEAdapter(); String template = FileUtils.readFileToString(new File("resources/templates/blackberry-smime-adapter.ftl")); autoTransactDelegator.setProperty("test@EXAMPLE.com", "pdfTemplate", template); mailetConfig.setInitParameter("log", "starting"); /* use some dummy template because we must specify the default template */ mailetConfig.setInitParameter("template", "sms.ftl"); mailetConfig.setInitParameter("templateProperty", "pdfTemplate"); mailet.init(mailetConfig);//from ww w.java 2 s .co m MockMail mail = new MockMail(); mail.setState(Mail.DEFAULT); MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/signed-opaque-validcertificate.eml")); mail.setMessage(message); Collection<MailAddress> recipients = new LinkedList<MailAddress>(); recipients.add(new MailAddress("123@EXAMPLE.com")); mail.setRecipients(recipients); mail.setSender(new MailAddress("sender@example.com")); mailet.service(mail); MailUtils.validateMessage(mail.getMessage()); TestUtils.saveMessages(tempDir, "testSMIMEAdaptMessage", mail.getMessage()); assertTrue(mail.getMessage().isMimeType("multipart/mixed")); assertFalse(mail.getMessage() == message); MimeMultipart mp = (MimeMultipart) mail.getMessage().getContent(); assertEquals(2, mp.getCount()); BodyPart bp = mp.getBodyPart(0); assertTrue(bp.isMimeType("text/plain")); bp = mp.getBodyPart(1); assertTrue(bp.isMimeType("application/octet-stream")); assertEquals("x-rimdevicesmime.p7m", bp.getFileName()); }
From source file:mitm.application.djigzo.james.mailets.BlackberrySMIMEAdapterTest.java
@Test public void testSMIMEAdaptMessageOverDirectLimit() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); SendMailEventListenerImpl listener = new SendMailEventListenerImpl(); mailetConfig.getMailetContext().setSendMailEventListener(listener); Mailet mailet = new BlackberrySMIMEAdapter(); String template = FileUtils.readFileToString(new File("resources/templates/blackberry-smime-adapter.ftl")); autoTransactDelegator.setProperty("test@EXAMPLE.com", "pdfTemplate", template); mailetConfig.setInitParameter("log", "starting"); /* use some dummy template because we must specify the default template */ mailetConfig.setInitParameter("template", "sms.ftl"); mailetConfig.setInitParameter("templateProperty", "pdfTemplate"); mailetConfig.setInitParameter("directSizeLimit", "100"); mailet.init(mailetConfig);/*from w w w. j a va 2 s.c o m*/ MockMail mail = new MockMail(); mail.setState(Mail.DEFAULT); MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/signed-opaque-validcertificate.eml")); mail.setMessage(message); Collection<MailAddress> recipients = new LinkedList<MailAddress>(); recipients.add(new MailAddress("123@EXAMPLE.com")); mail.setRecipients(recipients); mail.setSender(new MailAddress("sender@example.com")); mailet.service(mail); MailUtils.validateMessage(mail.getMessage()); TestUtils.saveMessages(tempDir, "testSMIMEAdaptMessageOverDirectLimit", mail.getMessage()); assertTrue(mail.getMessage().isMimeType("multipart/mixed")); assertFalse(mail.getMessage() == message); assertEquals("test 1,test 2", mail.getMessage().getHeader("X-Test", ",")); MimeMultipart mp = (MimeMultipart) mail.getMessage().getContent(); assertEquals(2, mp.getCount()); BodyPart bp = mp.getBodyPart(0); assertTrue(bp.isMimeType("text/plain")); bp = mp.getBodyPart(1); assertTrue(bp.isMimeType("application/octet-stream")); assertEquals("attachment.smime", bp.getFileName()); }
From source file:com.zimbra.cs.mime.Mime.java
public static MimePart getMimePart(MimePart mp, String part) throws IOException, MessagingException { if (mp == null) { return null; }//from w w w .j a v a 2s. c om if (part == null || part.trim().isEmpty()) { return mp; } part = part.trim(); boolean digestParent = false; String[] subpart = part.split("\\."); for (int i = 0; i < subpart.length; i++) { int index = Integer.parseInt(subpart[i]); if (index <= 0) { return null; } // the content-type determines the expected substructure String ct = getContentType(mp, digestParent ? MimeConstants.CT_MESSAGE_RFC822 : MimeConstants.CT_DEFAULT); if (ct == null) { return null; } digestParent = ct.equals(MimeConstants.CT_MULTIPART_DIGEST); if (ct.startsWith(MimeConstants.CT_MULTIPART_PREFIX)) { MimeMultipart mmp = getMultipartContent(mp, ct); if (mmp != null && mmp.getCount() >= index) { BodyPart bp = mmp.getBodyPart(index - 1); if (bp instanceof MimePart) { mp = (MimePart) bp; continue; } } } else if (ct.equals(MimeConstants.CT_MESSAGE_RFC822) || (ct.equals(MimeConstants.CT_APPLICATION_OCTET_STREAM) && isEmlAttachment(mp))) { MimeMessage content = getMessageContent(mp); if (content != null) { if (mp instanceof MimeMessage) { // the top-level part of a non-multipart message is numbered "1" if (index != 1) { return null; } } else { i--; } mp = content; continue; } } else if (mp instanceof MimeMessage && index == 1 && i == subpart.length - 1) { // the top-level part of a non-multipart message is numbered "1" break; } return null; } return mp; }
From source file:com.zimbra.cs.mime.Mime.java
private static List<MPartInfo> listParts(MimePart root, String defaultCharset) throws MessagingException, IOException { List<MPartInfo> parts = new ArrayList<MPartInfo>(); LinkedList<MPartInfo> queue = new LinkedList<MPartInfo>(); queue.add(generateMPartInfo(root, null, "", 0)); MimeMultipart emptyMultipart = null; while (!queue.isEmpty()) { MPartInfo mpart = queue.removeFirst(); MimePart mp = mpart.getMimePart(); parts.add(mpart);/*from w w w . ja v a 2 s.c om*/ String cts = mpart.mContentType; boolean isMultipart = cts.startsWith(MimeConstants.CT_MULTIPART_PREFIX); boolean isMessage = !isMultipart && cts.equals(MimeConstants.CT_MESSAGE_RFC822); if (isMultipart) { // IMAP part numbering is screwy: top-level multipart doesn't get a number String prefix = mpart.mPartName.length() > 0 ? (mpart.mPartName + '.') : ""; if (mp instanceof MimeMessage) { mpart.mPartName = prefix + "TEXT"; } MimeMultipart multi = getMultipartContent(mp, cts); if (multi != null) { if (multi.getCount() == 0 && LC.mime_promote_empty_multipart.booleanValue()) { if (emptyMultipart == null) { emptyMultipart = multi; } if (MimeConstants.CT_MULTIPART_APPLEDOUBLE.equalsIgnoreCase(getContentType(mp))) { ZimbraLog.misc.debug( "appledouble with no children; assuming it is malformed and really applefile"); mpart.mContentType = mpart.mContentType.replace(MimeConstants.CT_MULTIPART_APPLEDOUBLE, MimeConstants.CT_APPLEFILE); } } mpart.mChildren = new ArrayList<MPartInfo>(multi.getCount()); for (int i = 1; i <= multi.getCount(); i++) { mpart.mChildren .add(generateMPartInfo((MimePart) multi.getBodyPart(i - 1), mpart, prefix + i, i)); } queue.addAll(0, mpart.mChildren); } } else if (isMessage) { MimeMessage mm = getMessageContent(mp); if (mm != null) { MPartInfo child = generateMPartInfo(mm, mpart, mpart.mPartName, 0); queue.addFirst(child); mpart.mChildren = Arrays.asList(child); } } else { // nothing to do at this stage } } if (emptyMultipart != null && parts.size() == 1) { String text = emptyMultipart.getPreamble(); if (!StringUtil.isNullOrEmpty(text)) { ZimbraLog.misc .debug("single multipart with no children. promoting the preamble into a single text part"); parts.remove(0); MPartInfo mpart = new MPartInfo(); ZMimeBodyPart mp = new ZMimeBodyPart(); mp.setText(text, defaultCharset); mpart.mPart = mp; mpart.mContentType = mp.getContentType(); mpart.mDisposition = ""; mpart.mPartName = "1"; parts.add(mpart); } } return parts; }
From source file:de.betterform.connector.serializer.MultipartRelatedSerializer.java
protected void visitNode(Map cache, Node node, MimeMultipart multipart) throws Exception { ModelItem item = (ModelItem) node.getUserData(""); if (item != null && item.getDeclarationView().getDatatype() != null && item.getDeclarationView().getDatatype().equalsIgnoreCase("anyURI")) { String name = item.getFilename(); if (name == null || item.getValue() == null || item.getValue().equals("")) { return; }//from w w w . j a va 2s . com String cid = (String) cache.get(name); if (cid == null) { int count = multipart.getCount(); cid = name + "@part" + (count + 1); MimeBodyPart part = new MimeBodyPart(); part.setContentID("<" + cid + ">"); DataHandler dh = new DataHandler(new ModelItemDataSource(item)); part.setDataHandler(dh); part.addHeader("Content-Type", item.getMediatype()); part.addHeader("Content-Transfer-Encoding", "base64"); part.setDisposition("attachment"); part.setFileName(name); multipart.addBodyPart(part); cache.put(name, cid); } Element element = (Element) node; // remove text node NodeList list = node.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node n = list.item(i); if (n.getNodeType() != Node.TEXT_NODE) { continue; } n.setNodeValue("cid:" + cid); break; } } else { NodeList list = node.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node n = list.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { visitNode(cache, n, multipart); } } } }
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 a2 s . c o 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.eviware.soapui.impl.wsdl.submit.transports.http.MimeMessageResponse.java
public MimeMessageResponse(WsdlRequest wsdlRequest, final TimeablePostMethod postMethod, String requestContent) {/*from w w w . j a v a2 s .c o m*/ this.wsdlRequest = wsdlRequest; this.requestContent = requestContent; this.timeTaken = postMethod.getTimeTaken(); responseContentLength = postMethod.getResponseContentLength(); try { initHeaders(postMethod); MimeMultipart mp = new MimeMultipart(new PostResponseDataSource(postMethod)); message = new MimeMessage(HttpClientRequestTransport.JAVAMAIL_SESSION); message.setContent(mp); Header h = postMethod.getResponseHeader("Content-Type"); HeaderElement[] elements = h.getElements(); String rootPartId = null; for (HeaderElement element : elements) { if (element.getName().toUpperCase().startsWith("MULTIPART/")) { NameValuePair parameter = element.getParameterByName("start"); if (parameter != null) rootPartId = parameter.getValue(); } } for (int c = 0; c < mp.getCount(); c++) { BodyPart bodyPart = mp.getBodyPart(c); if (bodyPart.getContentType().toUpperCase().startsWith("MULTIPART/")) { MimeMultipart mp2 = new MimeMultipart(new BodyPartDataSource(bodyPart)); for (int i = 0; i < mp2.getCount(); i++) { result.add(new BodyPartAttachment(mp2.getBodyPart(i))); } } else { BodyPartAttachment attachment = new BodyPartAttachment(bodyPart); String[] contentIdHeaders = bodyPart.getHeader("Content-ID"); if (contentIdHeaders != null && contentIdHeaders.length > 0 && contentIdHeaders[0].equals(rootPartId)) { rootPart = attachment; } else result.add(attachment); } } // if no explicit root part has been set, use the first one in the result if (rootPart == null) rootPart = result.remove(0); if (wsdlRequest.getSettings().getBoolean(HttpSettings.INCLUDE_RESPONSE_IN_TIME_TAKEN)) this.timeTaken = postMethod.getTimeTakenUntilNow(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.icegreen.greenmail.store.SimpleMessageAttributes.java
/** * Parses key data items from a MimeMessage for seperate storage. * TODO this is a mess, and should be completely revamped. */// w w w .j a v a2s .c om void parseMimePart(MimePart part) throws MessagingException { size = GreenMailUtil.getBody(part).length(); // Section 1 - Message Headers if (part instanceof MimeMessage) { try { subject = ((MimeMessage) part).getSubject(); } catch (MessagingException me) { // if (DEBUG) getLogger().debug("Messaging Exception for getSubject: " + me); } } try { from = part.getHeader("From"); } catch (MessagingException me) { // if (DEBUG) getLogger().debug("Messaging Exception for getHeader(From): " + me); } try { sender = part.getHeader("Sender"); } catch (MessagingException me) { // if (DEBUG) getLogger().debug("Messaging Exception for getHeader(Sender): " + me); } try { replyTo = part.getHeader("Reply To"); } catch (MessagingException me) { // if (DEBUG) getLogger().debug("Messaging Exception for getHeader(Reply To): " + me); } try { to = part.getHeader("To"); } catch (MessagingException me) { // if (DEBUG) getLogger().debug("Messaging Exception for getHeader(To): " + me); } try { cc = part.getHeader("Cc"); } catch (MessagingException me) { // if (DEBUG) getLogger().debug("Messaging Exception for getHeader(To): " + me); } try { bcc = part.getHeader("Bcc"); } catch (MessagingException me) { // if (DEBUG) getLogger().debug("Messaging Exception for getHeader(To): " + me); } try { inReplyTo = part.getHeader("In Reply To"); } catch (MessagingException me) { // if (DEBUG) getLogger().debug("Messaging Exception for getHeader(In Reply To): " + me); } try { date = part.getHeader("Date"); } catch (MessagingException me) { // if (DEBUG) getLogger().debug("Messaging Exception for getHeader(Date): " + me); } try { messageID = part.getHeader("Message-ID"); } catch (MessagingException me) { // if (DEBUG) getLogger().debug("Messaging Exception for getHeader(messageID): " + me); } String contentTypeLine = null; try { contentTypeLine = part.getContentType(); } catch (MessagingException me) { // if (DEBUG) getLogger().debug("Messaging Exception for getContentType(): " + me); } if (contentTypeLine != null) { decodeContentType(contentTypeLine); } try { contentID = part.getContentID(); } catch (MessagingException me) { // if (DEBUG) getLogger().debug("Messaging Exception for getContentUD(): " + me); } try { contentDesc = part.getDescription(); } catch (MessagingException me) { // if (DEBUG) getLogger().debug("Messaging Exception for getDescription(): " + me); } try { contentEncoding = part.getEncoding(); // default value. if (contentEncoding == null) { contentEncoding = "7BIT"; } } catch (MessagingException me) { // if (DEBUG) getLogger().debug("Messaging Exception for getEncoding(): " + me); } try { // contentDisposition = part.getDisposition(); contentDisposition = Header.create(part.getHeader("Content-Disposition")); } catch (MessagingException me) { if (log.isDebugEnabled()) { log.debug("Can not create content disposition for part " + part, me); } } try { // TODO this doesn't work lineCount = getLineCount(part); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Can not get line count for part " + part, e); } } // Recurse through any embedded parts if (primaryType.equalsIgnoreCase(MULTIPART)) { MimeMultipart container; try { container = (MimeMultipart) part.getContent(); int count = container.getCount(); parts = new SimpleMessageAttributes[count]; for (int i = 0; i < count; i++) { BodyPart nextPart = container.getBodyPart(i); if (nextPart instanceof MimePart) { SimpleMessageAttributes partAttrs = new SimpleMessageAttributes(null, receivedDate); partAttrs.parseMimePart((MimePart) nextPart); parts[i] = partAttrs; } } } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Can not recurse through multipart content", e); } } } else if (primaryType.equalsIgnoreCase("message")) { if (secondaryType.equalsIgnoreCase("RFC822")) { //try { /* MimeMessageWrapper message = new MimeMessageWrapper(part.getInputStream()); SimpleMessageAttributes msgAttrs = new SimpleMessageAttributes(); msgAttrs.setAttributesFor(message); if (part instanceof MimeMessage) { Comments out because I don't know what it should do here MimeMessage msg1 = (MimeMessage) part; MimeMessageWrapper message2 = new MimeMessageWrapper(msg1); SimpleMessageAttributes msgAttrs2 = new SimpleMessageAttributes(); msgAttrs.setAttributesFor(message2); } parts = new SimpleMessageAttributes[1]; parts[0] = msgAttrs; */ //} catch (Exception e) { //getLogger().error("Error interpreting a message/rfc822: " + e); //e.printStackTrace(); //} // TODO: Warn till fixed! log.warn("Unknown/unhandled subtype " + secondaryType + " of message encountered."); } else { log.warn("Unknown/unhandled subtype " + secondaryType + " of message encountered."); } } }
From source file:mitm.application.djigzo.james.mailets.SMIMEEncryptTest.java
@Test public void testMultipartWithIllegalContentTransferEncoding() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); mailetConfig.setInitParameter("algorithm", "AES128"); SMIMEEncrypt mailet = new SMIMEEncrypt(); mailet.init(mailetConfig);/*from w w w. ja va2s . c om*/ Mail mail = new MockMail(); MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/quoted-printable-multipart.eml")); assertTrue(message.isMimeType("multipart/mixed")); MimeMultipart mp = (MimeMultipart) message.getContent(); assertEquals(2, mp.getCount()); BodyPart part = mp.getBodyPart(0); assertTrue(part.isMimeType("text/plain")); assertEquals("==", (String) part.getContent()); mail.setMessage(message); Set<MailAddress> recipients = new HashSet<MailAddress>(); recipients.add(new MailAddress("test@example.com")); mail.setRecipients(recipients); DjigzoMailAttributes mailAttributes = new DjigzoMailAttributesImpl(mail); mailAttributes.setCertificates(certificates); mailet.service(mail); MailUtils.validateMessage(mail.getMessage()); KeyStoreKeyProvider keyStore = new KeyStoreKeyProvider( loadKeyStore(new File("test/resources/testdata/keys/testCertificates.p12"), "test"), "test"); SMIMEInspector inspector = new SMIMEInspectorImpl(mail.getMessage(), keyStore, "BC"); assertEquals(SMIMEType.ENCRYPTED, inspector.getSMIMEType()); assertEquals(SMIMEEncryptionAlgorithm.AES128_CBC.getOID().toString(), inspector.getEnvelopedInspector().getEncryptionAlgorithmOID()); assertEquals(20, inspector.getEnvelopedInspector().getRecipients().size()); MimeMessage decrypted = inspector.getContentAsMimeMessage(); decrypted.saveChanges(); assertNotNull(decrypted); MailUtils.writeMessage(decrypted, new File(tempDir, "testMultipartWithIllegalContentTransferEncoding.eml")); assertTrue(decrypted.isMimeType("multipart/mixed")); mp = (MimeMultipart) decrypted.getContent(); assertEquals(2, mp.getCount()); part = mp.getBodyPart(0); assertTrue(part.isMimeType("text/plain")); /* * The body should not be changed to =3D=3D because the body should not be quoted-printable encoded * again */ assertEquals("==", (String) part.getContent()); }