List of usage examples for javax.mail.internet MimeMultipart getCount
@Override public synchronized int getCount() throws MessagingException
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!/* www . java 2s .c o m*/ * * @param multipart DOCUMENT ME! * @param text DOCUMENT ME! * @param charset DOCUMENT ME! * @param disposition DOCUMENT ME! * * @throws MessagingException DOCUMENT ME! */ public static void attach(MimeMultipart multipart, String text, String charset, String disposition, boolean isHtml) throws MessagingException { int xid = multipart.getCount() + 1; MimeBodyPart xbody = new MimeBodyPart(); String xname = null; if (isHtml) { xname = "HTML" + xid + ".html"; xbody.setContent(text, "text/html" + "; charset=" + charset); xbody.setDescription("Html Attachment: " + xname, charset); } else { xname = "TEXT" + xid + ".txt"; xbody.setText(text, charset); xbody.setDescription("Text Attachment: " + xname, charset); } // UNDONE //xbody.setContentLanguage( String ); // this could be language from Locale //xbody.setContentMD5( String md5 ); // don't know about this yet xbody.setDisposition(disposition); MessageUtilities.setFileName(xbody, xname, charset); multipart.addBodyPart(xbody); }
From source file:com.zimbra.cs.mime.Mime.java
private static MimeMultipart validateMultipart(MimeMultipart multi, MimePart mp) throws MessagingException, IOException { // our MIME parser preparses the multipart, so if an object exists then it's valid if (multi == null || isZimbraJavaMailShim(multi)) { return multi; }/*from w ww. ja va 2 s.co m*/ ContentType ctype = new ContentType(mp.getContentType()); try { if (!ctype.containsParameter("generated") && !findStartBoundary(mp, ctype.getParameter("boundary"))) { return new ZMimeMultipart(new RawContentMultipartDataSource(mp, ctype)); } multi.getCount(); } catch (ParseException pe) { multi = new ZMimeMultipart(new FixedMultipartDataSource(mp, ctype)); } catch (MessagingException me) { multi = new ZMimeMultipart(new FixedMultipartDataSource(mp, ctype)); } return multi; }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!/*from w w w . j av a2 s. c o m*/ * * @param multipart DOCUMENT ME! * @param part DOCUMENT ME! * @param charset DOCUMENT ME! * * @throws MessagingException DOCUMENT ME! */ public static void attach(MimeMultipart multipart, Part part, String charset) throws MessagingException { MimeBodyPart xbody = new MimeBodyPart(); PartDataSource xds = new PartDataSource(part); DataHandler xdh = new DataHandler(xds); xbody.setDataHandler(xdh); int xid = multipart.getCount() + 1; String xtext; // UNDONE //xbody.setContentLanguage( String ); // this could be language from Locale //xbody.setContentMD5( String md5 ); // don't know about this yet xtext = part.getDescription(); if (xtext == null) { xtext = "Part Attachment: " + xid; } xbody.setDescription(xtext, charset); xtext = getContentDisposition(part).getType(); xbody.setDisposition(xtext); xtext = MessageUtilities.getFileName(part); if ((xtext == null) || (xtext.length() < 1)) { xtext = "PART" + xid; } MessageUtilities.setFileName(xbody, xtext, charset); multipart.addBodyPart(xbody); }
From source file:com.eviware.soapui.impl.wsdl.submit.filters.WsdlPackagingRequestFilter.java
protected String initWsdlRequest(WsdlRequest wsdlRequest, ExtendedPostMethod postMethod, String requestContent) throws Exception { MimeMultipart mp = null; StringToStringMap contentIds = new StringToStringMap(); boolean isXOP = wsdlRequest.isMtomEnabled() && wsdlRequest.isForceMtom(); // preprocess only if neccessary if (wsdlRequest.isMtomEnabled() || wsdlRequest.isInlineFilesEnabled() || wsdlRequest.getAttachmentCount() > 0) { try {/*from w ww.j a v a 2 s.co m*/ mp = new MimeMultipart(); MessageXmlObject requestXmlObject = new MessageXmlObject(wsdlRequest.getOperation(), requestContent, true); MessageXmlPart[] requestParts = requestXmlObject.getMessageParts(); for (MessageXmlPart requestPart : requestParts) { if (AttachmentUtils.prepareMessagePart(wsdlRequest, mp, requestPart, contentIds)) isXOP = true; } requestContent = requestXmlObject.getMessageContent(); } catch (Throwable e) { SoapUI.log.warn("Failed to process inline/MTOM attachments; " + e); } } // non-multipart request? if (!isXOP && (mp == null || mp.getCount() == 0) && hasContentAttachmentsOnly(wsdlRequest)) { String encoding = System.getProperty("soapui.request.encoding", StringUtils.unquote(wsdlRequest.getEncoding())); byte[] content = StringUtils.isNullOrEmpty(encoding) ? requestContent.getBytes() : requestContent.getBytes(encoding); postMethod.setRequestEntity(new ByteArrayRequestEntity(content)); } else { // make sure.. if (mp == null) mp = new MimeMultipart(); // init root part initRootPart(wsdlRequest, requestContent, mp, isXOP); // init mimeparts AttachmentUtils.addMimeParts(wsdlRequest, Arrays.asList(wsdlRequest.getAttachments()), mp, contentIds); // create request message MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION); message.setContent(mp); message.saveChanges(); WsdlRequestMimeMessageRequestEntity mimeMessageRequestEntity = new WsdlRequestMimeMessageRequestEntity( message, isXOP, wsdlRequest); postMethod.setRequestEntity(mimeMessageRequestEntity); postMethod.setRequestHeader("Content-Type", mimeMessageRequestEntity.getContentType()); postMethod.setRequestHeader("MIME-Version", "1.0"); } return requestContent; }
From source file:de.mendelson.comm.as2.message.AS2MessageParser.java
/**Writes a passed payload part to the passed message object. *//*w w w . j av a 2s .c o m*/ public void writePayloadsToMessage(Part payloadPart, AS2Message message, Properties header) throws Exception { List<Part> attachmentList = new ArrayList<Part>(); AS2Info info = message.getAS2Info(); if (!info.isMDN()) { AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info(); if (payloadPart.isMimeType("multipart/*")) { //check if it is a CEM if (payloadPart.getContentType().toLowerCase().contains("application/ediint-cert-exchange+xml")) { messageInfo.setMessageType(AS2Message.MESSAGETYPE_CEM); if (this.logger != null) { this.logger.log(Level.FINE, this.rb.getResourceString("found.cem", new Object[] { messageInfo.getMessageId(), message }), info); } } ByteArrayOutputStream mem = new ByteArrayOutputStream(); payloadPart.writeTo(mem); mem.flush(); mem.close(); MimeMultipart multipart = new MimeMultipart( new ByteArrayDataSource(mem.toByteArray(), payloadPart.getContentType())); //add all attachments to the message for (int i = 0; i < multipart.getCount(); i++) { //its possible that one of the bodyparts is the signature (for compressed/signed messages), skip the signature if (!multipart.getBodyPart(i).getContentType().toLowerCase().contains("pkcs7-signature")) { attachmentList.add(multipart.getBodyPart(i)); } } } else { attachmentList.add(payloadPart); } } else { //its a MDN, write whole part attachmentList.add(payloadPart); } //write the parts for (Part attachmentPart : attachmentList) { ByteArrayOutputStream payloadOut = new ByteArrayOutputStream(); InputStream payloadIn = attachmentPart.getInputStream(); this.copyStreams(payloadIn, payloadOut); payloadOut.flush(); payloadOut.close(); byte[] data = payloadOut.toByteArray(); AS2Payload as2Payload = new AS2Payload(); as2Payload.setData(data); String[] contentIdHeader = attachmentPart.getHeader("content-id"); if (contentIdHeader != null && contentIdHeader.length > 0) { as2Payload.setContentId(contentIdHeader[0]); } String[] contentTypeHeader = attachmentPart.getHeader("content-type"); if (contentTypeHeader != null && contentTypeHeader.length > 0) { as2Payload.setContentType(contentTypeHeader[0]); } try { as2Payload.setOriginalFilename(payloadPart.getFileName()); } catch (MessagingException e) { if (this.logger != null) { this.logger.log(Level.WARNING, this.rb.getResourceString("filename.extraction.error", new Object[] { info.getMessageId(), e.getMessage(), }), info); } } if (as2Payload.getOriginalFilename() == null) { String filenameheader = header.getProperty("content-disposition"); if (filenameheader != null) { //test part for convinience: extract file name MimeBodyPart filenamePart = new MimeBodyPart(); filenamePart.setHeader("content-disposition", filenameheader); try { as2Payload.setOriginalFilename(filenamePart.getFileName()); } catch (MessagingException e) { if (this.logger != null) { this.logger.log(Level.WARNING, this.rb.getResourceString("filename.extraction.error", new Object[] { info.getMessageId(), e.getMessage(), }), info); } } } } message.addPayload(as2Payload); } }
From source file:de.mendelson.comm.as2.message.AS2MessageParser.java
/**Verifies the signature of the passed signed part*/ public MimeBodyPart verifySignedPart(Part signedPart, byte[] data, String contentType, X509Certificate certificate) throws Exception { BCCryptoHelper helper = new BCCryptoHelper(); String signatureTransferEncoding = null; MimeMultipart checkPart = (MimeMultipart) signedPart.getContent(); //it is sure that it is a signed part: set the type to multipart if the //parser has problems parsing it. Don't know why sometimes a parsing fails for //MimeBodyPart. This check looks if the parser is able to find more than one subpart if (checkPart.getCount() == 1) { MimeMultipart multipart = new MimeMultipart(new ByteArrayDataSource(data, contentType)); MimeMessage possibleSignedMessage = new MimeMessage(Session.getInstance(System.getProperties(), null)); possibleSignedMessage.setContent(multipart, multipart.getContentType()); possibleSignedMessage.saveChanges(); //overwrite the formerly found signed part signedPart = helper.getSignedEmbeddedPart(possibleSignedMessage); }/*from ww w.ja v a 2 s .c o m*/ //get the content encoding of the signature MimeMultipart signedMultiPart = (MimeMultipart) signedPart.getContent(); //body part 1 is always the signature String encodingHeader[] = signedMultiPart.getBodyPart(1).getHeader("Content-Transfer-Encoding"); if (encodingHeader != null) { signatureTransferEncoding = encodingHeader[0]; } return (helper.verify(signedPart, signatureTransferEncoding, certificate)); }
From source file:davmail.imap.ImapConnection.java
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 {/* ww w. j a va2s. com*/ 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("\")"); } }
From source file:davmail.imap.ImapConnection.java
private void handleFetch(ExchangeSession.Message message, int currentIndex, String parameters) throws IOException, MessagingException { StringBuilder buffer = new StringBuilder(); buffer.append("* ").append(currentIndex).append(" FETCH (UID ").append(message.getImapUid()); if (parameters != null) { StringTokenizer paramTokens = new StringTokenizer(parameters); while (paramTokens.hasMoreTokens()) { @SuppressWarnings({ "NonConstantStringShouldBeStringBuffer" }) String param = paramTokens.nextToken().toUpperCase(); if ("FLAGS".equals(param)) { buffer.append(" FLAGS (").append(message.getImapFlags()).append(')'); } else if ("RFC822.SIZE".equals(param)) { int size; if (parameters.indexOf("BODY.PEEK[HEADER.FIELDS (") >= 0) { // Header request, send approximate size size = message.size; } else { size = message.getMimeMessageSize(); }/*www .j a v a 2 s. c om*/ buffer.append(" RFC822.SIZE ").append(size); } else if ("ENVELOPE".equals(param)) { appendEnvelope(buffer, message); } else if ("BODYSTRUCTURE".equals(param)) { appendBodyStructure(buffer, message); } else if ("INTERNALDATE".equals(param) && message.date != null && message.date.length() > 0) { try { SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); dateParser.setTimeZone(ExchangeSession.GMT_TIMEZONE); Date date = ExchangeSession.getZuluDateFormat().parse(message.date); SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss Z", Locale.ENGLISH); buffer.append(" INTERNALDATE \"").append(dateFormatter.format(date)).append('\"'); } catch (ParseException e) { throw new DavMailException("EXCEPTION_INVALID_DATE", message.date); } } else if (param.equals("RFC822") || param.startsWith("BODY[") || param.startsWith("BODY.PEEK[") || "RFC822.HEADER".equals(param)) { // get full param if (param.indexOf('[') >= 0) { StringBuilder paramBuffer = new StringBuilder(param); while (paramTokens.hasMoreTokens() && paramBuffer.indexOf("]") < 0) { paramBuffer.append(' ').append(paramTokens.nextToken()); } param = paramBuffer.toString(); } // parse buffer size int startIndex = 0; int maxSize = Integer.MAX_VALUE; int ltIndex = param.indexOf('<'); if (ltIndex >= 0) { int dotIndex = param.indexOf('.', ltIndex); if (dotIndex >= 0) { startIndex = Integer.parseInt(param.substring(ltIndex + 1, dotIndex)); maxSize = Integer.parseInt(param.substring(dotIndex + 1, param.indexOf('>'))); } } ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream partInputStream = null; OutputStream partOutputStream = null; // try to parse message part index String partIndexString = StringUtil.getToken(param, "[", "]"); if ("".equals(partIndexString) || partIndexString == null) { // write message with headers partOutputStream = new PartialOutputStream(baos, startIndex, maxSize); partInputStream = message.getRawInputStream(); } else if ("TEXT".equals(partIndexString)) { // write message without headers partOutputStream = new PartialOutputStream(baos, startIndex, maxSize); partInputStream = message.getMimeMessage().getRawInputStream(); } else if ("RFC822.HEADER".equals(param) || partIndexString.startsWith("HEADER")) { // Header requested fetch headers String[] requestedHeaders = getRequestedHeaders(partIndexString); if (requestedHeaders != null) { // OSX Lion special flags request if (requestedHeaders.length == 1 && "content-class".equals(requestedHeaders[0]) && message.contentClass != null) { baos.write("Content-class: ".getBytes("UTF-8")); baos.write(message.contentClass.getBytes("UTF-8")); baos.write(13); baos.write(10); } else { Enumeration headerEnumeration = message.getMatchingHeaderLines(requestedHeaders); while (headerEnumeration.hasMoreElements()) { baos.write(((String) headerEnumeration.nextElement()).getBytes("UTF-8")); baos.write(13); baos.write(10); } } } else { // write headers only partOutputStream = new PartOutputStream(baos, true, false, startIndex, maxSize); partInputStream = message.getRawInputStream(); } } else { MimePart bodyPart = message.getMimeMessage(); String[] partIndexStrings = partIndexString.split("\\."); for (String subPartIndexString : partIndexStrings) { // ignore MIME subpart index, will return full part if ("MIME".equals(subPartIndexString)) { break; } int subPartIndex; // try to parse part index try { subPartIndex = Integer.parseInt(subPartIndexString); } catch (NumberFormatException e) { throw new DavMailException("EXCEPTION_INVALID_PARAMETER", param); } Object mimeBody = bodyPart.getContent(); if (mimeBody instanceof MimeMultipart) { MimeMultipart multiPart = (MimeMultipart) mimeBody; if (subPartIndex - 1 < multiPart.getCount()) { bodyPart = (MimePart) multiPart.getBodyPart(subPartIndex - 1); } else { throw new DavMailException("EXCEPTION_INVALID_PARAMETER", param); } } else if (subPartIndex != 1) { throw new DavMailException("EXCEPTION_INVALID_PARAMETER", param); } } // write selected part, without headers partOutputStream = new PartialOutputStream(baos, startIndex, maxSize); if (bodyPart instanceof MimeMessage) { partInputStream = ((MimeMessage) bodyPart).getRawInputStream(); } else { partInputStream = ((MimeBodyPart) bodyPart).getRawInputStream(); } } // copy selected content to baos if (partInputStream != null && partOutputStream != null) { IOUtil.write(partInputStream, partOutputStream); partInputStream.close(); partOutputStream.close(); } baos.close(); if ("RFC822.HEADER".equals(param)) { buffer.append(" RFC822.HEADER "); } else { buffer.append(" BODY[").append(partIndexString).append(']'); } // partial if (startIndex > 0 || maxSize != Integer.MAX_VALUE) { buffer.append('<').append(startIndex).append('>'); } buffer.append(" {").append(baos.size()).append('}'); sendClient(buffer.toString()); // log content if less than 2K if (LOGGER.isDebugEnabled() && baos.size() < 2048) { LOGGER.debug(new String(baos.toByteArray(), "UTF-8")); } os.write(baos.toByteArray()); os.flush(); buffer.setLength(0); } } } buffer.append(')'); sendClient(buffer.toString()); // do not keep message content in memory message.dropMimeMessage(); }
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.// www . j av a 2s . 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; }