List of usage examples for javax.mail.internet MimeMultipart getBodyPart
public synchronized BodyPart getBodyPart(String CID) throws MessagingException
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. com 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: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 a2s . c om*/ //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:de.mendelson.comm.as2.message.AS2MessageParser.java
/**Writes a passed payload part to the passed message object. *///from w w w. jav a2 s .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: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 ww w. j a v a2 s . co m*/ 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:org.liveSense.service.email.EmailServiceImpl.java
/** * {@inheritDoc}/*from w w w . ja va 2 s.co m*/ */ @Override public void sendEmailFromTemplateString(Session session, String template, Node resource, String subject, Object replyTo, Object from, Date date, Object[] to, Object[] cc, Object[] bcc, HashMap<String, Object> variables) throws Exception { boolean haveSession = false; try { if (session != null && session.isLive()) { haveSession = true; } else { session = repository.loginAdministrative(null); } if (template == null) { throw new RepositoryException("Template is null"); } String html = templateNode(Md5Encrypter.encrypt(template), resource, template, variables); if (html == null) throw new RepositoryException("Template is empty"); // create the messge. MimeMessage mimeMessage = new MimeMessage((javax.mail.Session) null); MimeMultipart rootMixedMultipart = new MimeMultipart("mixed"); mimeMessage.setContent(rootMixedMultipart); MimeMultipart nestedRelatedMultipart = new MimeMultipart("related"); MimeBodyPart relatedBodyPart = new MimeBodyPart(); relatedBodyPart.setContent(nestedRelatedMultipart); rootMixedMultipart.addBodyPart(relatedBodyPart); MimeMultipart messageBody = new MimeMultipart("alternative"); MimeBodyPart bodyPart = null; for (int i = 0; i < nestedRelatedMultipart.getCount(); i++) { BodyPart bp = nestedRelatedMultipart.getBodyPart(i); if (bp.getFileName() == null) { bodyPart = (MimeBodyPart) bp; } } if (bodyPart == null) { MimeBodyPart mimeBodyPart = new MimeBodyPart(); nestedRelatedMultipart.addBodyPart(mimeBodyPart); bodyPart = mimeBodyPart; } bodyPart.setContent(messageBody, "text/alternative"); // Create the plain text part of the message. MimeBodyPart plainTextPart = new MimeBodyPart(); plainTextPart.setText(extractTextFromHtml(html), configurator.getEncoding()); messageBody.addBodyPart(plainTextPart); // Create the HTML text part of the message. MimeBodyPart htmlTextPart = new MimeBodyPart(); htmlTextPart.setContent(html, "text/html;charset=" + configurator.getEncoding()); // ;charset=UTF-8 messageBody.addBodyPart(htmlTextPart); // Check if resource have nt:file childs adds as attachment if (resource != null && resource.hasNodes()) { NodeIterator iter = resource.getNodes(); while (iter.hasNext()) { Node n = iter.nextNode(); if (n.getPrimaryNodeType().isNodeType("nt:file")) { // Part two is attachment MimeBodyPart attachmentBodyPart = new MimeBodyPart(); InputStream fileData = n.getNode("jcr:content").getProperty("jcr:data").getBinary() .getStream(); String mimeType = n.getNode("jcr:content").getProperty("jcr:mimeType").getString(); String fileName = n.getName(); DataSource source = new StreamDataSource(fileData, fileName, mimeType); attachmentBodyPart.setDataHandler(new DataHandler(source)); attachmentBodyPart.setFileName(fileName); attachmentBodyPart.setDisposition(MimeBodyPart.ATTACHMENT); attachmentBodyPart.setContentID(fileName); rootMixedMultipart.addBodyPart(attachmentBodyPart); } } } prepareMimeMessage(mimeMessage, resource, template, subject, replyTo, from, date, to, cc, bcc, variables); sendEmail(session, mimeMessage); // } finally { if (!haveSession && session != null) { if (session.hasPendingChanges()) { try { session.save(); } catch (Throwable th) { } } session.logout(); } } }
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 {/*from w ww . j a va 2 s.c o m*/ 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(); }// w w w. ja v a2s . 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.//from ww w . j a v a 2 s . c o 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:davmail.exchange.dav.DavExchangeSession.java
/** * Create message in specified folder.// w w w .j a va 2s. com * Will overwrite an existing message with same messageName in the same folder * * @param folderPath Exchange folder path * @param messageName message name * @param properties message properties (flags) * @param mimeMessage MIME message * @throws IOException when unable to create message */ @Override public void createMessage(String folderPath, String messageName, HashMap<String, String> properties, MimeMessage mimeMessage) throws IOException { String messageUrl = URIUtil.encodePathQuery(getFolderPath(folderPath) + '/' + messageName); PropPatchMethod patchMethod; List<PropEntry> davProperties = buildProperties(properties); if (properties != null && properties.containsKey("draft")) { // note: draft is readonly after create, create the message first with requested messageFlags davProperties.add(Field.createDavProperty("messageFlags", properties.get("draft"))); } if (properties != null && properties.containsKey("mailOverrideFormat")) { davProperties.add(Field.createDavProperty("mailOverrideFormat", properties.get("mailOverrideFormat"))); } if (properties != null && properties.containsKey("messageFormat")) { davProperties.add(Field.createDavProperty("messageFormat", properties.get("messageFormat"))); } if (!davProperties.isEmpty()) { patchMethod = new PropPatchMethod(messageUrl, davProperties); try { // update message with blind carbon copy and other flags int statusCode = httpClient.executeMethod(patchMethod); if (statusCode != HttpStatus.SC_MULTI_STATUS) { throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, statusCode, ' ', patchMethod.getStatusLine()); } } finally { patchMethod.releaseConnection(); } } // update message body PutMethod putmethod = new PutMethod(messageUrl); putmethod.setRequestHeader("Translate", "f"); putmethod.setRequestHeader("Content-Type", "message/rfc822"); try { // use same encoding as client socket reader ByteArrayOutputStream baos = new ByteArrayOutputStream(); mimeMessage.writeTo(baos); baos.close(); putmethod.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray())); int code = httpClient.executeMethod(putmethod); // workaround for misconfigured Exchange server if (code == HttpStatus.SC_NOT_ACCEPTABLE) { LOGGER.warn( "Draft message creation failed, failover to property update. Note: attachments are lost"); ArrayList<PropEntry> propertyList = new ArrayList<PropEntry>(); propertyList.add(Field.createDavProperty("to", mimeMessage.getHeader("to", ","))); propertyList.add(Field.createDavProperty("cc", mimeMessage.getHeader("cc", ","))); propertyList.add(Field.createDavProperty("message-id", mimeMessage.getHeader("message-id", ","))); MimePart mimePart = mimeMessage; if (mimeMessage.getContent() instanceof MimeMultipart) { MimeMultipart multiPart = (MimeMultipart) mimeMessage.getContent(); for (int i = 0; i < multiPart.getCount(); i++) { String contentType = multiPart.getBodyPart(i).getContentType(); if (contentType.startsWith("text/")) { mimePart = (MimePart) multiPart.getBodyPart(i); break; } } } String contentType = mimePart.getContentType(); if (contentType.startsWith("text/plain")) { propertyList.add(Field.createDavProperty("description", (String) mimePart.getContent())); } else if (contentType.startsWith("text/html")) { propertyList.add(Field.createDavProperty("htmldescription", (String) mimePart.getContent())); } else { LOGGER.warn("Unsupported content type: " + contentType + " message body will be empty"); } propertyList.add(Field.createDavProperty("subject", mimeMessage.getHeader("subject", ","))); PropPatchMethod propPatchMethod = new PropPatchMethod(messageUrl, propertyList); try { int patchStatus = DavGatewayHttpClientFacade.executeHttpMethod(httpClient, propPatchMethod); if (patchStatus == HttpStatus.SC_MULTI_STATUS) { code = HttpStatus.SC_OK; } } finally { propPatchMethod.releaseConnection(); } } if (code != HttpStatus.SC_OK && code != HttpStatus.SC_CREATED) { // first delete draft message if (!davProperties.isEmpty()) { try { DavGatewayHttpClientFacade.executeDeleteMethod(httpClient, messageUrl); } catch (IOException e) { LOGGER.warn("Unable to delete draft message"); } } if (code == HttpStatus.SC_INSUFFICIENT_STORAGE) { throw new InsufficientStorageException(putmethod.getStatusText()); } else { throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, code, ' ', putmethod.getStatusLine()); } } } catch (MessagingException e) { throw new IOException(e.getMessage()); } finally { putmethod.releaseConnection(); } try { // need to update bcc after put if (mimeMessage.getHeader("Bcc") != null) { davProperties = new ArrayList<PropEntry>(); davProperties.add(Field.createDavProperty("bcc", mimeMessage.getHeader("Bcc", ","))); patchMethod = new PropPatchMethod(messageUrl, davProperties); try { // update message with blind carbon copy int statusCode = httpClient.executeMethod(patchMethod); if (statusCode != HttpStatus.SC_MULTI_STATUS) { throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, statusCode, ' ', patchMethod.getStatusLine()); } } finally { patchMethod.releaseConnection(); } } } catch (MessagingException e) { throw new IOException(e.getMessage()); } }