List of usage examples for javax.mail Part getHeader
public String[] getHeader(String header_name) throws MessagingException;
From source file:com.sonicle.webtop.mail.Service.java
public String getPartName(Part p) throws MessagingException { String pname = p.getFileName(); // TODO: Remove code below if already included in JavaMail impl. if (pname == null) { String hctypes[] = p.getHeader("Content-Type"); if (hctypes == null || hctypes.length == 0) { return null; }//from w w w . j a va2 s .co m String hctype = hctypes[0]; int ix = hctype.indexOf("name="); if (ix >= 0) { int sx = ix + 5; int ex = hctype.indexOf(";", sx); if (ex >= 0) { pname = hctype.substring(sx, ex); } else { pname = hctype.substring(sx); } pname = pname.trim(); int xx = pname.length() - 1; if (pname.charAt(0) == '"' && pname.charAt(xx) == '"') { pname = pname.substring(1, xx); } } if (pname == null) { return null; } logger.warn("Code in getPartName is still used. Please review it!"); try { pname = MimeUtility.decodeText(pname); } catch (UnsupportedEncodingException ex) { Service.logger.error("Exception", ex); } } return pname; }
From source file:com.sonicle.webtop.mail.Service.java
public void processGetReplyMessage(HttpServletRequest request, HttpServletResponse response, PrintWriter out) { MailAccount account = getAccount(request); UserProfile profile = environment.getProfile(); //WebTopApp webtopapp=environment.getWebTopApp(); String pfoldername = request.getParameter("folder"); String puidmessage = request.getParameter("idmessage"); String preplyall = request.getParameter("replyall"); boolean replyAll = false; if (preplyall != null && preplyall.equals("1")) { replyAll = true;//www. j a v a2s .co m } String sout = null; try { String format = us.getFormat(); boolean isHtml = format.equals("html"); account.checkStoreConnected(); FolderCache mcache = account.getFolderCache(pfoldername); Message m = mcache.getMessage(Long.parseLong(puidmessage)); if (m.isExpunged()) { throw new MessagingException("Message " + puidmessage + " expunged"); } int newmsgid = getNewMessageID(); SimpleMessage smsg = getReplyMsg(getNewMessageID(), account, m, replyAll, account.isSentFolder(pfoldername), isHtml, profile.getEmailAddress(), mprofile.isIncludeMessageInReply(), lookupResource(MailLocaleKey.MSG_FROMTITLE), lookupResource(MailLocaleKey.MSG_TOTITLE), lookupResource(MailLocaleKey.MSG_CCTITLE), lookupResource(MailLocaleKey.MSG_DATETITLE), lookupResource(MailLocaleKey.MSG_SUBJECTTITLE)); sout = "{\n result: true,"; Identity ident = mprofile.getIdentity(pfoldername); String inreplyto = smsg.getInReplyTo(); String references[] = smsg.getReferences(); sout += " replyfolder: '" + StringEscapeUtils.escapeEcmaScript(pfoldername) + "',"; if (inreplyto != null) { sout += " inreplyto: '" + StringEscapeUtils.escapeEcmaScript(inreplyto) + "',"; } if (references != null) { String refs = ""; for (String s : references) { refs += StringEscapeUtils.escapeEcmaScript(s) + " "; } sout += " references: '" + refs.trim() + "',"; } String subject = smsg.getSubject(); sout += " subject: '" + StringEscapeUtils.escapeEcmaScript(subject) + "',\n"; sout += " recipients: [\n"; String tos[] = smsg.getTo().split(";"); boolean first = true; for (String to : tos) { if (!first) { sout += ",\n"; } sout += " {rtype:'to',email:'" + StringEscapeUtils.escapeEcmaScript(to) + "'}"; first = false; } String ccs[] = smsg.getCc().split(";"); for (String cc : ccs) { if (!first) { sout += ",\n"; } sout += " {rtype:'cc',email:'" + StringEscapeUtils.escapeEcmaScript(cc) + "'}"; first = false; } sout += "\n ],\n"; sout += " identityId: " + ident.getIdentityId() + ",\n"; sout += " origuid:" + puidmessage + ",\n"; if (isHtml) { String html = smsg.getContent(); //cid inline attachments and relative html href substitution HTMLMailData maildata = mcache.getMailData((MimeMessage) m); first = true; sout += " attachments: [\n"; for (int i = 0; i < maildata.getAttachmentPartCount(); ++i) { try { Part part = maildata.getAttachmentPart(i); String filename = getPartName(part); String cids[] = part.getHeader("Content-ID"); if (cids != null && cids[0] != null) { String cid = cids[0]; if (cid.startsWith("<")) cid = cid.substring(1); if (cid.endsWith(">")) cid = cid.substring(0, cid.length() - 1); String mime = MailUtils.getMediaTypeFromHeader(part.getContentType()); UploadedFile upfile = addAsUploadedFile("" + newmsgid, filename, mime, part.getInputStream()); if (!first) { sout += ",\n"; } sout += "{ " + " uploadId: '" + StringEscapeUtils.escapeEcmaScript(upfile.getUploadId()) + "', " + " fileName: '" + StringEscapeUtils.escapeEcmaScript(filename) + "', " + " cid: '" + StringEscapeUtils.escapeEcmaScript(cid) + "', " + " inline: true, " + " fileSize: " + upfile.getSize() + ", " + " editable: " + isFileEditableInDocEditor(filename) + " " + " }"; first = false; //TODO: change this weird matching of cids2urls! html = StringUtils.replace(html, "cid:" + cid, "service-request?csrf=" + getEnv().getCSRFToken() + "&service=" + SERVICE_ID + "&action=PreviewAttachment&nowriter=true&uploadId=" + upfile.getUploadId() + "&cid=" + cid); } } catch (Exception exc) { Service.logger.error("Exception", exc); } } sout += "\n ],\n"; sout += " content:'" + StringEscapeUtils.escapeEcmaScript(html) + "',\n"; } else { String text = smsg.getTextContent(); sout += " content:'" + StringEscapeUtils.escapeEcmaScript(text) + "',\n"; } sout += " format:'" + format + "'\n"; sout += "\n}"; } catch (Exception exc) { Service.logger.error("Exception", exc); sout = "{\nresult: false, text:'" + StringEscapeUtils.escapeEcmaScript(exc.getMessage()) + "'\n}"; } if (sout != null) { out.println(sout); } }
From source file:com.sonicle.webtop.mail.Service.java
public void processGetForwardMessage(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {// w ww.ja va2 s .c om MailAccount account = getAccount(request); UserProfile profile = environment.getProfile(); String pfoldername = request.getParameter("folder"); String puidmessage = request.getParameter("idmessage"); String pnewmsgid = request.getParameter("newmsgid"); String pattached = request.getParameter("attached"); boolean attached = (pattached != null && pattached.equals("1")); long newmsgid = Long.parseLong(pnewmsgid); String sout = null; try { String format = us.getFormat(); boolean isHtml = format.equals("html"); account.checkStoreConnected(); FolderCache mcache = account.getFolderCache(pfoldername); Message m = mcache.getMessage(Long.parseLong(puidmessage)); if (m.isExpunged()) { throw new MessagingException("Message " + puidmessage + " expunged"); } SimpleMessage smsg = getForwardMsg(newmsgid, m, isHtml, lookupResource(MailLocaleKey.MSG_FROMTITLE), lookupResource(MailLocaleKey.MSG_TOTITLE), lookupResource(MailLocaleKey.MSG_CCTITLE), lookupResource(MailLocaleKey.MSG_DATETITLE), lookupResource(MailLocaleKey.MSG_SUBJECTTITLE), attached); sout = "{\n result: true,"; Identity ident = mprofile.getIdentity(pfoldername); String forwardedfrom = smsg.getForwardedFrom(); sout += " forwardedfolder: '" + StringEscapeUtils.escapeEcmaScript(pfoldername) + "',"; if (forwardedfrom != null) { sout += " forwardedfrom: '" + StringEscapeUtils.escapeEcmaScript(forwardedfrom) + "',"; } String subject = smsg.getSubject(); sout += " subject: '" + StringEscapeUtils.escapeEcmaScript(subject) + "',\n"; String html = smsg.getContent(); String text = smsg.getTextContent(); if (!attached) { HTMLMailData maildata = mcache.getMailData((MimeMessage) m); boolean first = true; sout += " attachments: [\n"; for (int i = 0; i < maildata.getAttachmentPartCount(); ++i) { try { Part part = maildata.getAttachmentPart(i); String filename = getPartName(part); if (!part.isMimeType("message/*")) { String cids[] = part.getHeader("Content-ID"); String cid = null; //String cid=filename; if (cids != null && cids[0] != null) { cid = cids[0]; if (cid.startsWith("<")) cid = cid.substring(1); if (cid.endsWith(">")) cid = cid.substring(0, cid.length() - 1); } if (filename == null) filename = cid; String mime = MailUtils.getMediaTypeFromHeader(part.getContentType()); UploadedFile upfile = addAsUploadedFile(pnewmsgid, filename, mime, part.getInputStream()); boolean inline = false; if (part.getDisposition() != null) { inline = part.getDisposition().equalsIgnoreCase(Part.INLINE); } if (!first) { sout += ",\n"; } sout += "{ " + " uploadId: '" + StringEscapeUtils.escapeEcmaScript(upfile.getUploadId()) + "', " + " fileName: '" + StringEscapeUtils.escapeEcmaScript(filename) + "', " + " cid: " + (cid == null ? null : "'" + StringEscapeUtils.escapeEcmaScript(cid) + "'") + ", " + " inline: " + inline + ", " + " fileSize: " + upfile.getSize() + ", " + " editable: " + isFileEditableInDocEditor(filename) + " " + " }"; first = false; //TODO: change this weird matching of cids2urls! html = StringUtils.replace(html, "cid:" + cid, "service-request?csrf=" + getEnv().getCSRFToken() + "&service=" + SERVICE_ID + "&action=PreviewAttachment&nowriter=true&uploadId=" + upfile.getUploadId() + "&cid=" + cid); } } catch (Exception exc) { Service.logger.error("Exception", exc); } } sout += "\n ],\n"; //String surl = "service-request?service="+SERVICE_ID+"&action=PreviewAttachment&nowriter=true&newmsgid=" + newmsgid + "&cid="; //html = replaceCidUrls(html, maildata, surl); } else { String filename = m.getSubject() + ".eml"; UploadedFile upfile = addAsUploadedFile(pnewmsgid, filename, "message/rfc822", ((IMAPMessage) m).getMimeStream()); sout += " attachments: [\n"; sout += "{ " + " uploadId: '" + StringEscapeUtils.escapeEcmaScript(upfile.getUploadId()) + "', " + " fileName: '" + StringEscapeUtils.escapeEcmaScript(filename) + "', " + " cid: null, " + " inline: false, " + " fileSize: " + upfile.getSize() + ", " + " editable: " + isFileEditableInDocEditor(filename) + " " + " }"; sout += "\n ],\n"; } sout += " identityId: " + ident.getIdentityId() + ",\n"; sout += " origuid:" + puidmessage + ",\n"; if (isHtml) { sout += " content:'" + StringEscapeUtils.escapeEcmaScript(html) + "',\n"; } else { sout += " content:'" + StringEscapeUtils.escapeEcmaScript(text) + "',\n"; } sout += " format:'" + format + "'\n"; sout += "\n}"; out.println(sout); } catch (Exception exc) { Service.logger.error("Exception", exc); sout = "{\nresult: false, text:'" + StringEscapeUtils.escapeEcmaScript(exc.getMessage()) + "'\n}"; out.println(sout); } }
From source file:com.sonicle.webtop.mail.Service.java
public void processGetEditMessage(HttpServletRequest request, HttpServletResponse response, PrintWriter out) { MailAccount account = getAccount(request); String pfoldername = request.getParameter("folder"); String puidmessage = request.getParameter("idmessage"); String pnewmsgid = request.getParameter("newmsgid"); long newmsgid = Long.parseLong(pnewmsgid); String sout = null;//from www.j ava2 s .co m try { MailEditFormat editFormat = ServletUtils.getEnumParameter(request, "format", null, MailEditFormat.class); if (editFormat == null) editFormat = EnumUtils.forSerializedName(us.getFormat(), MailEditFormat.HTML, MailEditFormat.class); boolean isPlainEdit = MailEditFormat.PLAIN_TEXT.equals(editFormat); account.checkStoreConnected(); FolderCache mcache = account.getFolderCache(pfoldername); IMAPMessage m = (IMAPMessage) mcache.getMessage(Long.parseLong(puidmessage)); m.setPeek(us.isManualSeen()); //boolean wasseen = m.isSet(Flags.Flag.SEEN); String vheader[] = m.getHeader("Disposition-Notification-To"); boolean receipt = false; int priority = 3; boolean recipients = false; boolean toDelete = false; if (account.isDraftsFolder(pfoldername)) { if (vheader != null && vheader[0] != null) { receipt = true; } priority = getPriority(m); recipients = true; //if autosaved drafts, delete String values[] = m.getHeader(HEADER_X_WEBTOP_MSGID); if (values != null && values.length > 0) { try { long msgId = Long.parseLong(values[0]); if (msgId > 0) { toDelete = true; } } catch (NumberFormatException exc) { } } } sout = "{\n result: true,"; String subject = m.getSubject(); if (subject == null) { subject = ""; } sout += " subject: '" + StringEscapeUtils.escapeEcmaScript(subject) + "',\n"; String inreplyto = null; String references[] = null; String vs[] = m.getHeader("In-Reply-To"); if (vs != null && vs[0] != null) { inreplyto = vs[0]; } references = m.getHeader("References"); if (inreplyto != null) { vs = m.getHeader("Sonicle-reply-folder"); String replyfolder = null; if (vs != null && vs[0] != null) { replyfolder = vs[0]; } if (replyfolder != null) { sout += " replyfolder: '" + StringEscapeUtils.escapeEcmaScript(replyfolder) + "',"; } sout += " inreplyto: '" + StringEscapeUtils.escapeEcmaScript(inreplyto) + "',"; } if (references != null) { String refs = ""; for (String s : references) { refs += StringEscapeUtils.escapeEcmaScript(s) + " "; } sout += " references: '" + refs.trim() + "',"; } String forwardedfrom = null; vs = m.getHeader("Forwarded-From"); if (vs != null && vs[0] != null) { forwardedfrom = vs[0]; } if (forwardedfrom != null) { vs = m.getHeader("Sonicle-forwarded-folder"); String forwardedfolder = null; if (vs != null && vs[0] != null) { forwardedfolder = vs[0]; } if (forwardedfolder != null) { sout += " forwardedfolder: '" + StringEscapeUtils.escapeEcmaScript(forwardedfolder) + "',"; } sout += " forwardedfrom: '" + StringEscapeUtils.escapeEcmaScript(forwardedfrom) + "',"; } sout += " receipt: " + receipt + ",\n"; sout += " priority: " + (priority >= 3 ? false : true) + ",\n"; Identity ident = null; Address from[] = m.getFrom(); InternetAddress iafrom = null; if (from != null && from.length > 0) { iafrom = (InternetAddress) from[0]; String email = iafrom.getAddress(); String displayname = iafrom.getPersonal(); if (displayname == null) displayname = email; //sout+=" from: { email: '"+StringEscapeUtils.escapeEcmaScript(email)+"', displayname: '"+StringEscapeUtils.escapeEcmaScript(displayname)+"' },\n"; ident = mprofile.getIdentity(displayname, email); } sout += " recipients: [\n"; if (recipients) { Address tos[] = m.getRecipients(RecipientType.TO); String srec = ""; if (tos != null) { for (Address to : tos) { if (srec.length() > 0) { srec += ",\n"; } srec += " { " + "rtype: 'to', " + "email: '" + StringEscapeUtils.escapeEcmaScript(getDecodedAddress(to)) + "'" + " }"; } } Address ccs[] = m.getRecipients(RecipientType.CC); if (ccs != null) { for (Address cc : ccs) { if (srec.length() > 0) { srec += ",\n"; } srec += " { " + "rtype: 'cc', " + "email: '" + StringEscapeUtils.escapeEcmaScript(getDecodedAddress(cc)) + "'" + " }"; } } Address bccs[] = m.getRecipients(RecipientType.BCC); if (bccs != null) { for (Address bcc : bccs) { if (srec.length() > 0) { srec += ",\n"; } srec += " { " + "rtype: 'bcc', " + "email: '" + StringEscapeUtils.escapeEcmaScript(getDecodedAddress(bcc)) + "'" + " }"; } } sout += srec; } else { sout += " { " + "rtype: 'to', " + "email: ''" + " }"; } sout += " ],\n"; String html = ""; boolean balanceTags = isPreviewBalanceTags(iafrom); ArrayList<String> htmlparts = mcache.getHTMLParts((MimeMessage) m, newmsgid, true, balanceTags); for (String xhtml : htmlparts) { html += xhtml + "<BR><BR>"; } HTMLMailData maildata = mcache.getMailData((MimeMessage) m); //if(!wasseen){ // if (us.isManualSeen()) { // m.setFlag(Flags.Flag.SEEN, false); // } //} boolean first = true; sout += " attachments: [\n"; for (int i = 0; i < maildata.getAttachmentPartCount(); ++i) { Part part = maildata.getAttachmentPart(i); String filename = getPartName(part); String cids[] = part.getHeader("Content-ID"); String cid = null; //String cid=filename; if (cids != null && cids[0] != null) { cid = cids[0]; if (cid.startsWith("<")) cid = cid.substring(1); if (cid.endsWith(">")) cid = cid.substring(0, cid.length() - 1); } if (filename == null) { filename = cid; } String mime = part.getContentType(); UploadedFile upfile = addAsUploadedFile(pnewmsgid, filename, mime, part.getInputStream()); boolean inline = false; if (part.getDisposition() != null) { inline = part.getDisposition().equalsIgnoreCase(Part.INLINE); } if (!first) { sout += ",\n"; } sout += "{ " + " uploadId: '" + StringEscapeUtils.escapeEcmaScript(upfile.getUploadId()) + "', " + " fileName: '" + StringEscapeUtils.escapeEcmaScript(filename) + "', " + " cid: " + (cid == null ? null : "'" + StringEscapeUtils.escapeEcmaScript(cid) + "'") + ", " + " inline: " + inline + ", " + " fileSize: " + upfile.getSize() + " " + " }"; first = false; //TODO: change this weird matching of cids2urls! html = StringUtils.replace(html, "cid:" + cid, "service-request?csrf=" + getEnv().getCSRFToken() + "&service=" + SERVICE_ID + "&action=PreviewAttachment&nowriter=true&uploadId=" + upfile.getUploadId() + "&cid=" + cid); } sout += "\n ],\n"; if (ident != null) sout += " identityId: " + ident.getIdentityId() + ",\n"; sout += " origuid:" + puidmessage + ",\n"; sout += " deleted:" + toDelete + ",\n"; sout += " folder:'" + pfoldername + "',\n"; sout += " content:'" + (isPlainEdit ? StringEscapeUtils.escapeEcmaScript(MailUtils.htmlToText(MailUtils.htmlunescapesource(html))) : StringEscapeUtils.escapeEcmaScript(html)) + "',\n"; sout += " format:'" + EnumUtils.toSerializedName(editFormat) + "'\n"; sout += "\n}"; m.setPeek(false); if (toDelete) { m.setFlag(Flags.Flag.DELETED, true); m.getFolder().expunge(); } out.println(sout); } catch (Exception exc) { Service.logger.error("Exception", exc); sout = "{\nresult: false, text:'" + StringEscapeUtils.escapeEcmaScript(exc.getMessage()) + "'\n}"; } }
From source file:com.sonicle.webtop.mail.Service.java
private boolean appendReplyParts(Part p, StringBuffer htmlsb, StringBuffer textsb, ArrayList<String> attnames) throws MessagingException, IOException { boolean isHtml = false; String disp = p.getDisposition(); if (disp != null && disp.equalsIgnoreCase(Part.ATTACHMENT) && !p.isMimeType("message/*")) { if (attnames != null) {/*from ww w . j a v a2 s . c om*/ String id[] = p.getHeader("Content-ID"); if (id == null || id[0] == null) { String filename = p.getFileName(); if (filename != null) { if (filename.startsWith("<")) { filename = filename.substring(1); } if (filename.endsWith(">")) { filename = filename.substring(0, filename.length() - 1); } } if (filename != null) { attnames.add(filename); } } } return false; } if (p.isMimeType("text/html")) { //String htmlcontent=(String)p.getContent(); String htmlcontent = getTextContentAsString(p); textsb.append(MailUtils.htmlToText(MailUtils.htmlunescapesource(htmlcontent))); htmlsb.append(MailUtils.htmlescapefixsource(/*getBodyInnerHtml(*/htmlcontent/*)*/)); isHtml = true; } else if (p.isMimeType("text/plain")) { String content = getTextContentAsString(p); textsb.append(content); htmlsb.append(startpre + MailUtils.htmlescape(content) + endpre); isHtml = false; } else if (p.isMimeType("message/delivery-status") || p.isMimeType("message/disposition-notification")) { InputStream is = (InputStream) p.getContent(); char cbuf[] = new char[8000]; byte bbuf[] = new byte[8000]; int n = 0; htmlsb.append(startpre); while ((n = is.read(bbuf)) >= 0) { if (n > 0) { for (int i = 0; i < n; ++i) { cbuf[i] = (char) bbuf[i]; } textsb.append(cbuf); htmlsb.append(MailUtils.htmlescape(new String(cbuf))); } } htmlsb.append(endpre); is.close(); isHtml = false; } else if (p.isMimeType("multipart/alternative")) { Multipart mp = (Multipart) p.getContent(); Part bestPart = null; for (int i = 0; i < mp.getCount(); ++i) { Part part = mp.getBodyPart(i); if (part.isMimeType("multipart/*")) { isHtml = appendReplyParts(part, htmlsb, textsb, attnames); if (isHtml) { bestPart = null; break; } } else if (part.isMimeType("text/html")) { bestPart = part; break; } else if (bestPart == null && part.isMimeType("text/plain")) { bestPart = part; } else if (bestPart == null && part.isMimeType("message/*")) { bestPart = part; } } if (bestPart != null) { isHtml = appendReplyParts(bestPart, htmlsb, textsb, attnames); } } else if (p.isMimeType("multipart/*")) { Multipart mp = (Multipart) p.getContent(); for (int i = 0; i < mp.getCount(); ++i) { if (appendReplyParts(mp.getBodyPart(i), htmlsb, textsb, attnames)) { isHtml = true; } } } else if (p.isMimeType("message/*")) { Object content = p.getContent(); if (appendReplyParts((MimeMessage) content, htmlsb, textsb, attnames)) { isHtml = true; } } else { } textsb.append('\n'); textsb.append('\n'); return isHtml; }
From source file:com.sonicle.webtop.mail.Service.java
public void processGetMessage(HttpServletRequest request, HttpServletResponse response, PrintWriter out) { MailAccount account = getAccount(request); String pfoldername = request.getParameter("folder"); String puidmessage = request.getParameter("idmessage"); String pidattach = request.getParameter("idattach"); String providername = request.getParameter("provider"); String providerid = request.getParameter("providerid"); String nopec = request.getParameter("nopec"); int idattach = 0; boolean isEditor = request.getParameter("editor") != null; boolean setSeen = ServletUtils.getBooleanParameter(request, "setseen", true); if (df == null) { df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.MEDIUM, environment.getProfile().getLocale()); }//w ww . j a va2 s . co m try { FolderCache mcache = null; Message m = null; IMAPMessage im = null; int recs = 0; long msguid = -1; String vheader[] = null; boolean wasseen = false; boolean isPECView = false; String sout = "{\nmessage: [\n"; if (providername == null) { account.checkStoreConnected(); mcache = account.getFolderCache(pfoldername); msguid = Long.parseLong(puidmessage); m = mcache.getMessage(msguid); im = (IMAPMessage) m; im.setPeek(us.isManualSeen()); if (m.isExpunged()) throw new MessagingException("Message " + puidmessage + " expunged"); vheader = m.getHeader("Disposition-Notification-To"); wasseen = m.isSet(Flags.Flag.SEEN); if (pidattach != null) { HTMLMailData mailData = mcache.getMailData((MimeMessage) m); Part part = mailData.getAttachmentPart(Integer.parseInt(pidattach)); m = (Message) part.getContent(); idattach = Integer.parseInt(pidattach) + 1; } else if (nopec == null && mcache.isPEC()) { String hdrs[] = m.getHeader(HDR_PEC_TRASPORTO); if (hdrs != null && hdrs.length > 0 && hdrs[0].equals("posta-certificata")) { HTMLMailData mailData = mcache.getMailData((MimeMessage) m); int parts = mailData.getAttachmentPartCount(); for (int i = 0; i < parts; ++i) { Part p = mailData.getAttachmentPart(i); if (p.isMimeType("message/rfc822")) { m = (Message) p.getContent(); idattach = i + 1; isPECView = true; break; } } } } } else { // TODO: provider get message!!!! /* WebTopService provider=wts.getServiceByName(providername); MessageContentProvider mcp=provider.getMessageContentProvider(providerid); m=new MimeMessage(session,mcp.getSource()); mcache=fcProvided; mcache.addProvidedMessage(providername, providerid, m);*/ } String messageid = getMessageID(m); String subject = m.getSubject(); if (subject == null) { subject = ""; } else { try { subject = MailUtils.decodeQString(subject); } catch (Exception exc) { } } java.util.Date d = m.getSentDate(); if (d == null) { d = m.getReceivedDate(); } if (d == null) { d = new java.util.Date(0); } String date = df.format(d).replaceAll("\\.", ":"); String fromName = ""; String fromEmail = ""; Address as[] = m.getFrom(); InternetAddress iafrom = null; if (as != null && as.length > 0) { iafrom = (InternetAddress) as[0]; fromName = iafrom.getPersonal(); fromEmail = adjustEmail(iafrom.getAddress()); if (fromName == null) { fromName = fromEmail; } } sout += "{iddata:'from',value1:'" + StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(fromName)) + "',value2:'" + StringEscapeUtils.escapeEcmaScript(fromEmail) + "',value3:0},\n"; recs += 2; Address tos[] = m.getRecipients(RecipientType.TO); if (tos != null) { for (Address to : tos) { InternetAddress ia = (InternetAddress) to; String toName = ia.getPersonal(); String toEmail = adjustEmail(ia.getAddress()); if (toName == null) { toName = toEmail; } sout += "{iddata:'to',value1:'" + StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(toName)) + "',value2:'" + StringEscapeUtils.escapeEcmaScript(toEmail) + "',value3:0},\n"; ++recs; } } Address ccs[] = m.getRecipients(RecipientType.CC); if (ccs != null) { for (Address cc : ccs) { InternetAddress ia = (InternetAddress) cc; String ccName = ia.getPersonal(); String ccEmail = adjustEmail(ia.getAddress()); if (ccName == null) { ccName = ccEmail; } sout += "{iddata:'cc',value1:'" + StringEscapeUtils.escapeEcmaScript(ccName) + "',value2:'" + StringEscapeUtils.escapeEcmaScript(ccEmail) + "',value3:0},\n"; ++recs; } } Address bccs[] = m.getRecipients(RecipientType.BCC); if (bccs != null) for (Address bcc : bccs) { InternetAddress ia = (InternetAddress) bcc; String bccName = ia.getPersonal(); String bccEmail = adjustEmail(ia.getAddress()); if (bccName == null) { bccName = bccEmail; } sout += "{iddata:'bcc',value1:'" + StringEscapeUtils.escapeEcmaScript(bccName) + "',value2:'" + StringEscapeUtils.escapeEcmaScript(bccEmail) + "',value3:0},\n"; ++recs; } ArrayList<String> htmlparts = null; boolean balanceTags = isPreviewBalanceTags(iafrom); if (providername == null) { htmlparts = mcache.getHTMLParts((MimeMessage) m, msguid, false, balanceTags); } else { htmlparts = mcache.getHTMLParts((MimeMessage) m, providername, providerid, balanceTags); } HTMLMailData mailData = mcache.getMailData((MimeMessage) m); ICalendarRequest ir = mailData.getICalRequest(); if (ir != null) { if (htmlparts.size() > 0) sout += "{iddata:'html',value1:'" + StringEscapeUtils.escapeEcmaScript(htmlparts.get(0)) + "',value2:'',value3:0},\n"; } else { for (String html : htmlparts) { //sout += "{iddata:'html',value1:'" + OldUtils.jsEscape(html) + "',value2:'',value3:0},\n"; sout += "{iddata:'html',value1:'" + StringEscapeUtils.escapeEcmaScript(html) + "',value2:'',value3:0},\n"; ++recs; } } /*if (!wasseen) { //if (us.isManualSeen()) { if (!setSeen) { m.setFlag(Flags.Flag.SEEN, false); } else { //if no html part, flag seen is not set if (htmlparts.size()==0) m.setFlag(Flags.Flag.SEEN, true); } }*/ if (!us.isManualSeen()) { if (htmlparts.size() == 0) m.setFlag(Flags.Flag.SEEN, true); } else { if (setSeen) m.setFlag(Flags.Flag.SEEN, true); } int acount = mailData.getAttachmentPartCount(); for (int i = 0; i < acount; ++i) { Part p = mailData.getAttachmentPart(i); String ctype = p.getContentType(); Service.logger.debug("attachment " + i + " is " + ctype); int ix = ctype.indexOf(';'); if (ix > 0) { ctype = ctype.substring(0, ix); } String cidnames[] = p.getHeader("Content-ID"); String cidname = null; if (cidnames != null && cidnames.length > 0) cidname = mcache.normalizeCidFileName(cidnames[0]); boolean isInlineable = isInlineableMime(ctype); boolean inline = ((p.getHeader("Content-Location") != null) || (cidname != null)) && isInlineable; if (inline && cidname != null) inline = mailData.isReferencedCid(cidname); if (p.getDisposition() != null && p.getDisposition().equalsIgnoreCase(Part.INLINE) && inline) { continue; } String imgname = null; boolean isCalendar = ctype.equalsIgnoreCase("text/calendar") || ctype.equalsIgnoreCase("text/icalendar"); if (isCalendar) { imgname = "resources/" + getManifest().getId() + "/laf/" + cus.getLookAndFeel() + "/ical_16.png"; } String pname = getPartName(p); try { pname = MailUtils.decodeQString(pname); } catch (Exception exc) { } if (pname == null) { ix = ctype.indexOf("/"); String fname = ctype; if (ix > 0) { fname = ctype.substring(ix + 1); } //String ext = WT.getMediaTypeExtension(ctype); //if (ext == null) { pname = fname; //} else { // pname = fname + "." + ext; //} if (isCalendar) pname += ".ics"; } else { if (isCalendar && !StringUtils.endsWithIgnoreCase(pname, ".ics")) pname += ".ics"; } int size = p.getSize(); int lines = (size / 76); int rsize = size - (lines * 2);//(p.getSize()/4)*3; String iddata = ctype.equalsIgnoreCase("message/rfc822") ? "eml" : (inline ? "inlineattach" : "attach"); boolean editable = isFileEditableInDocEditor(pname); sout += "{iddata:'" + iddata + "',value1:'" + (i + idattach) + "',value2:'" + StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(pname)) + "',value3:" + rsize + ",value4:" + (imgname == null ? "null" : "'" + StringEscapeUtils.escapeEcmaScript(imgname) + "'") + ", editable: " + editable + " },\n"; } if (!mcache.isDrafts() && !mcache.isSent() && !mcache.isSpam() && !mcache.isTrash() && !mcache.isArchive()) { if (vheader != null && vheader[0] != null && !wasseen) { sout += "{iddata:'receipt',value1:'" + us.getReadReceiptConfirmation() + "',value2:'" + StringEscapeUtils.escapeEcmaScript(vheader[0]) + "',value3:0},\n"; } } String h = getSingleHeaderValue(m, "Sonicle-send-scheduled"); if (h != null && h.equals("true")) { java.util.Calendar scal = parseScheduleHeader(getSingleHeaderValue(m, "Sonicle-send-date"), getSingleHeaderValue(m, "Sonicle-send-time")); if (scal != null) { java.util.Date sd = scal.getTime(); String sdate = df.format(sd).replaceAll("\\.", ":"); sout += "{iddata:'scheddate',value1:'" + StringEscapeUtils.escapeEcmaScript(sdate) + "',value2:'',value3:0},\n"; } } if (ir != null) { /* ICalendarManager calMgr = (ICalendarManager)WT.getServiceManager("com.sonicle.webtop.calendar",environment.getProfileId()); if (calMgr != null) { if (ir.getMethod().equals("REPLY")) { calMgr.updateEventFromICalReply(ir.getCalendar()); //TODO: gestire lato client una notifica di avvenuto aggiornamento } else { Event evt = calMgr..getEvent(GetEventScope.PERSONAL_AND_INCOMING, false, ir.getUID()) if (evt != null) { UserProfileId pid = getEnv().getProfileId(); UserProfile.Data ud = WT.getUserData(pid); boolean iAmOrganizer = StringUtils.equalsIgnoreCase(evt.getOrganizerAddress(), ud.getEmailAddress()); boolean iAmOwner = pid.equals(calMgr.getCalendarOwner(evt.getCalendarId())); if (!iAmOrganizer && !iAmOwner) { //TODO: gestire lato client l'aggiornamento: Accetta/Rifiuta, Aggiorna e20 dopo update/request } } } } */ ICalendarManager cm = (ICalendarManager) WT.getServiceManager("com.sonicle.webtop.calendar", true, environment.getProfileId()); if (cm != null) { int eid = -1; //Event ev=cm.getEventByScope(EventScope.PERSONAL_AND_INCOMING, ir.getUID()); Event ev = null; if (ir.getMethod().equals("REPLY")) { // Previous impl. forced (forceOriginal == true) ev = cm.getEvent(GetEventScope.PERSONAL_AND_INCOMING, ir.getUID()); } else { ev = cm.getEvent(GetEventScope.PERSONAL_AND_INCOMING, ir.getUID()); } UserProfileId pid = getEnv().getProfileId(); UserProfile.Data ud = WT.getUserData(pid); if (ev != null) { InternetAddress organizer = InternetAddressUtils.toInternetAddress(ev.getOrganizer()); boolean iAmOwner = pid.equals(cm.getCalendarOwner(ev.getCalendarId())); boolean iAmOrganizer = (organizer != null) && StringUtils.equalsIgnoreCase(organizer.getAddress(), ud.getEmailAddress()); //TODO: in reply controllo se mail combacia con quella dell'attendee che risponde... //TODO: rimuovere controllo su data? dovrebbe sempre aggiornare? if (iAmOwner || iAmOrganizer) { eid = 0; //TODO: troviamo un modo per capire se la risposta si riverisce all'ultima versione dell'evento? Nuovo campo timestamp? /* DateTime dtEvt = ev.getRevisionTimestamp().withMillisOfSecond(0).withZone(DateTimeZone.UTC); DateTime dtICal = ICal4jUtils.fromICal4jDate(ir.getLastModified(), ICal4jUtils.getTimeZone(DateTimeZone.UTC)); if (dtICal.isAfter(dtEvt)) { eid = 0; } else { eid = ev.getEventId(); } */ } } sout += "{iddata:'ical',value1:'" + ir.getMethod() + "',value2:'" + ir.getUID() + "',value3:'" + eid + "'},\n"; } } sout += "{iddata:'date',value1:'" + StringEscapeUtils.escapeEcmaScript(date) + "',value2:'',value3:0},\n"; sout += "{iddata:'subject',value1:'" + StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(subject)) + "',value2:'',value3:0},\n"; sout += "{iddata:'messageid',value1:'" + StringEscapeUtils.escapeEcmaScript(messageid) + "',value2:'',value3:0}\n"; if (providername == null && !mcache.isSpecial()) { mcache.refreshUnreads(); } long millis = System.currentTimeMillis(); sout += "\n],\n"; String svtags = getJSTagsArray(m.getFlags()); if (svtags != null) sout += "tags: " + svtags + ",\n"; if (isPECView) { sout += "pec: true,\n"; } sout += "total:" + recs + ",\nmillis:" + millis + "\n}\n"; out.println(sout); if (im != null) im.setPeek(false); // if (!wasopen) folder.close(false); } catch (Exception exc) { Service.logger.error("Exception", exc); } }
From source file:net.wastl.webmail.server.WebMailSession.java
/** Use depth-first search to go through MIME-Parts recursively. @param p Part to begin with//from w w w . j a va2 s .c om */ protected void parseMIMEContent(Part p, XMLMessagePart parent_part, String msgid) throws MessagingException { StringBuilder content = new StringBuilder(1000); XMLMessagePart xml_part; try { if (p.getContentType().toUpperCase().startsWith("TEXT/HTML")) { /* The part is a text in HTML format. We will try to use "Tidy" to create a well-formatted XHTML DOM from it and then remove JavaScript and other "evil" stuff. For replying to such a message, it will be useful to just remove all of the tags and display only the text. */ xml_part = parent_part.createPart("html"); /**************************************************** * LEAVING THESE OLD XML PARSERS COMMENTED OUT * until know that the new Parser tactic parses HTML properly * (or adequately). See the ** comment below. /* Here we create a DOM tree. //Tidy tidy=new Tidy(); //tidy.setUpperCaseTags(true); //Document htmldoc=tidy.parseDOM(p.getInputStream(),null); // org.cyberneko.html.parsers.DOMParser parser = // new org.cyberneko.html.parsers.DOMParser(); // DOMParser parser = new DOMParser(new HTMLConfiguration()); // parser.parse(new InputSource(p.getInputStream())); // Document htmldoc = parser.getDocument(); // instantiate a DOM implementation DOM dom = new com.docuverse.dom.DOM(); // install the SAX driver for Swing HTML parser dom.setProperty("sax.driver", "com.docuverse.html.swing.SAXDriver"); // install HTML element factory dom.setFactory(new com.docuverse.dom.html.HTMLFactory()); // ** N.B. WITH docuverse AND NekoHTML, THE PARSER WAS // HTML-Specific. We are now using generic XML parser. // Is that adequate? // now just open the document Document htmldoc = (Document)dom.readDocument(p.getInputStream()); */ javax.xml.parsers.DocumentBuilder parser = javax.xml.parsers.DocumentBuilderFactory.newInstance() .newDocumentBuilder(); Document htmldoc = parser.parse(p.getInputStream()); if (htmldoc == null) { log.error("Document was null!"); // Why not throwing? } //dom.writeDocument(htmldoc,"/tmp/test.xml"); /* Now let's look for all the malicious JavaScript and other <SCRIPT> tags, URLS containing the "javascript:" and tags containing "onMouseOver" and such stuff. */ // if(user.getBoolVar("filter javascript")) new JavaScriptCleaner(htmldoc); new JavaScriptCleaner(htmldoc); //dom.writeDocument(htmldoc,"/tmp/test2.xml"); //XMLCommon.debugXML(htmldoc); /* HTML doesn't allow us to do such fancy stuff like different quote colors, perhaps this will be implemented in the future */ /* So we just add this HTML document to the message part, which will deal with removing headers and tags that we don't need */ xml_part.addContent(htmldoc); } else if (p.getContentType().toUpperCase().startsWith("TEXT") || p.getContentType().toUpperCase().startsWith("MESSAGE")) { /* The part is a standard message part in some incarnation of text (html or plain). We should decode it and take care of some extra issues like recognize quoted parts, filter JavaScript parts and replace smileys with smiley-icons if the user has set wantsFancy() */ xml_part = parent_part.createPart("text"); // TODO: log.debug("text hit"); BufferedReader in; if (p instanceof MimeBodyPart) { int size = p.getSize(); MimeBodyPart mpb = (MimeBodyPart) p; InputStream is = mpb.getInputStream(); /* Workaround for Java or Javamail Bug */ is = new BufferedInputStream(is); ByteStore ba = ByteStore.getBinaryFromIS(is, size); in = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(ba.getBytes()))); /* End of workaround */ size = is.available(); } else { in = new BufferedReader(new InputStreamReader(p.getInputStream())); } log.debug("Content-Type: " + p.getContentType()); String token = ""; int quote_level = 0, old_quotelevel = 0; boolean javascript_mode = false; /* Read in the message part line by line */ while ((token = in.readLine()) != null) { /* First decode all language and MIME dependant stuff */ // Default to ISO-8859-1 (Western Latin 1) String charset = "ISO-8859-1"; // Check whether the part contained a charset in the content-type header StringTokenizer tok2 = new StringTokenizer(p.getContentType(), ";="); String blah = tok2.nextToken(); if (tok2.hasMoreTokens()) { blah = tok2.nextToken().trim(); if (blah.toLowerCase().equals("charset") && tok2.hasMoreTokens()) { charset = tok2.nextToken().trim(); } } try { token = new String(token.getBytes(), charset); } catch (UnsupportedEncodingException ex1) { log.info("Java Engine does not support charset " + charset + ". Trying to convert from MIME ..."); try { charset = MimeUtility.javaCharset(charset); token = new String(token.getBytes(), charset); } catch (UnsupportedEncodingException ex) { log.warn("Converted charset (" + charset + ") does not work. Using default charset (ouput may contain errors)"); token = new String(token.getBytes()); } } /* Here we figure out which quote level this line has, simply by counting how many ">" are in front of the line, ignoring all whitespaces. */ int current_quotelevel = Helper.getQuoteLevel(token); /* When we are in a different quote level than the last line, we append all we got so far to the part with the old quotelevel and begin with a clean String buffer */ if (current_quotelevel != old_quotelevel) { xml_part.addContent(content.toString(), old_quotelevel); old_quotelevel = current_quotelevel; content = new StringBuilder(1000); } if (user.wantsBreakLines()) { Enumeration enumVar = Helper.breakLine(token, user.getMaxLineLength(), current_quotelevel); while (enumVar.hasMoreElements()) { String s = (String) enumVar.nextElement(); if (user.wantsShowFancy()) { content.append(Fancyfier.apply(s)).append("\n"); } else { content.append(s).append("\n"); } } } else { if (user.wantsShowFancy()) { content.append(Fancyfier.apply(token)).append("\n"); } else { content.append(token).append("\n"); } } } xml_part.addContent(content.toString(), old_quotelevel); // Why the following code??? content = new StringBuilder(1000); } else if (p.getContentType().toUpperCase().startsWith("MULTIPART/ALTERNATIVE")) { /* This is a multipart/alternative part. That means that we should pick one of the formats and display it for this part. Our current precedence list is to choose HTML first and then to choose plain text. */ MimeMultipart m = (MimeMultipart) p.getContent(); String[] preferred = { "TEXT/HTML", "TEXT" }; boolean found = false; int alt = 0; // Walk though our preferred list of encodings. If we have found a fitting part, // decode it and replace it for the parent (this is what we really want with an // alternative!) /** findalt: while(!found && alt < preferred.length) { for(int i=0;i<m.getCount();i++) { Part p2=m.getBodyPart(i); if(p2.getContentType().toUpperCase().startsWith(preferred[alt])) { parseMIMEContent(p2,parent_part,msgid); found=true; break findalt; } } alt++; } **/ /** * When user try to reply a mail, there may be 3 conditions: * 1. only TEXT exists. * 2. both HTML and TEXT exist. * 3. only HTML exists. * * We have to choose which part should we quote, that is, we must * decide the prority of parts to quote. Since quoting HTML is not * easy and precise (consider a html: <body><div><b>some text..</b> * </div></body>. Even we try to get text node under <body>, we'll * just get nothing, because "some text..." is marked up by * <div><b>. There is no easy way to retrieve text from html * unless we parse the html to analyse its semantics. * * Here is our policy for alternative part: * 1. Displays HTML but hides TEXT. * 2. When replying this mail, try to quote TEXT part. If no TEXT * part exists, quote HTML in best effort(use * XMLMessagePart.quoteContent() by Sebastian Schaffert.) */ while (alt < preferred.length) { for (int i = 0; i < m.getCount(); i++) { Part p2 = m.getBodyPart(i); if (p2.getContentType().toUpperCase().startsWith(preferred[alt])) { log.debug("Processing: " + p2.getContentType()); parseMIMEContent(p2, parent_part, msgid); found = true; break; } } /** * If we've selected HTML part from alternative part, the TEXT * part should be hidden from display but keeping in XML for * later quoting operation. * * Of course, this requires some modification on showmessage.xsl. */ if (found && (alt == 1)) { Node textPartNode = parent_part.getPartElement().getLastChild(); NamedNodeMap attributes = textPartNode.getAttributes(); boolean hit = false; for (int i = 0; i < attributes.getLength(); ++i) { Node attr = attributes.item(i); // If type=="TEXT", add a hidden attribute. if (attr.getNodeName().toUpperCase().equals("TYPE") && attr.getNodeValue().toUpperCase().equals("TEXT")) { ((Element) textPartNode).setAttribute("hidden", "true"); } } } alt++; } if (!found) { // If we didn't find one of our preferred encodings, choose the first one // simply pass the parent part because replacement is what we really want with // an alternative. parseMIMEContent(m.getBodyPart(0), parent_part, msgid); } } else if (p.getContentType().toUpperCase().startsWith("MULTIPART/")) { /* This is a standard multipart message. We should recursively walk thorugh all of the parts and decode them, appending as children to the current part */ xml_part = parent_part.createPart("multi"); MimeMultipart m = (MimeMultipart) p.getContent(); for (int i = 0; i < m.getCount(); i++) { parseMIMEContent(m.getBodyPart(i), xml_part, msgid); } } else { /* Else treat the part as a binary part that the user should either download or get displayed immediately in case of an image */ InputStream in = null; String type = ""; if (p.getContentType().toUpperCase().startsWith("IMAGE/JPG") || p.getContentType().toUpperCase().startsWith("IMAGE/JPEG")) { type = "jpg"; xml_part = parent_part.createPart("image"); } else if (p.getContentType().toUpperCase().startsWith("IMAGE/GIF")) { type = "gif"; xml_part = parent_part.createPart("image"); } else if (p.getContentType().toUpperCase().startsWith("IMAGE/PNG")) { type = "png"; xml_part = parent_part.createPart("image"); } else { xml_part = parent_part.createPart("binary"); } int size = p.getSize(); if (p instanceof MimeBodyPart) { MimeBodyPart mpb = (MimeBodyPart) p; log.debug("MIME Body part (image), Encoding: " + mpb.getEncoding()); InputStream is = mpb.getInputStream(); /* Workaround for Java or Javamail Bug */ in = new BufferedInputStream(is); ByteStore ba = ByteStore.getBinaryFromIS(in, size); in = new ByteArrayInputStream(ba.getBytes()); /* End of workaround */ size = in.available(); } else { log.warn("No MIME Body part!!"); // Is this unexpected? Consider changing log level. in = p.getInputStream(); } ByteStore data = ByteStore.getBinaryFromIS(in, size); if (mime_parts_decoded == null) { mime_parts_decoded = new HashMap<String, ByteStore>(); } String name = p.getFileName(); if (name == null || name.equals("")) { // Try an other way String headers[] = p.getHeader("Content-Disposition"); int pos = -1; if (headers.length == 1) { pos = headers[0].indexOf("filename*=") + 10; } if (pos != -1) { int charsetEnds = headers[0].indexOf("''", pos); String charset = headers[0].substring(pos, charsetEnds); String encodedFileName = headers[0].substring(charsetEnds + 2); encodedFileName = "=?" + charset + "?Q?" + encodedFileName.replace('%', '=') + "?="; name = MimeUtility.decodeText(encodedFileName); } else { name = "unknown." + type; } } // Eliminate space characters. Should do some more things in the future name = name.replace(' ', '_'); data.setContentType(p.getContentType()); data.setContentEncoding("BINARY"); mime_parts_decoded.put(msgid + "/" + name, data); /** * For multibytes language system, we have to separate filename into * 2 format: one for display (UTF-8 encoded), another for encode the * url of hyperlink. * `filename' is for display, while `hrefFileName' is for hyperlink. * To make use of these two attributes, `showmessage.xsl' is slightly * modified. */ data.setName(name); xml_part.setAttribute("filename", name); // Transcode name into UTF-8 bytes then make a new ISO8859_1 string to encode URL. xml_part.setAttribute("hrefFileName", name); xml_part.setAttribute("size", size + ""); String description = p.getDescription() == null ? "" : p.getDescription(); xml_part.setAttribute("description", description); StringTokenizer tok = new StringTokenizer(p.getContentType(), ";"); xml_part.setAttribute("content-type", tok.nextToken().toLowerCase()); } } catch (java.io.IOException ex) { log.error("Failed to parse mime content", ex); } catch (MessagingException ex) { log.error("Failed to parse mime content", ex); } catch (Exception ex) { log.error("Failed to parse mime content", ex); } }
From source file:org.alfresco.repo.content.transform.EMLParser.java
/** * Adapted extract multipart is the recusrsive parser that splits the data and apend it to the * final xhtml file./*from w w w . ja va 2 s .co m*/ * * @param xhtml * the xhtml * @param part * the part * @param parentPart * the parent part * @param context * the context * @throws MessagingException * the messaging exception * @throws IOException * Signals that an I/O exception has occurred. * @throws SAXException * the sAX exception * @throws TikaException * the tika exception */ public void adaptedExtractMultipart(XHTMLContentHandler xhtml, Part part, Part parentPart, ParseContext context) throws MessagingException, IOException, SAXException, TikaException { String disposition = part.getDisposition(); if ((disposition != null && disposition.contains(Part.ATTACHMENT))) { return; } if (part.isMimeType("text/plain")) { if (parentPart != null && parentPart.isMimeType(MULTIPART_ALTERNATIVE)) { return; } else { // add file String data = part.getContent().toString(); writeContent(part, data, MimetypeMap.MIMETYPE_TEXT_PLAIN, "txt"); } } else if (part.isMimeType("multipart/*")) { Multipart mp = (Multipart) part.getContent(); Part parentPartLocal = part; if (parentPart != null && parentPart.isMimeType(MULTIPART_ALTERNATIVE)) { parentPartLocal = parentPart; } int count = mp.getCount(); for (int i = 0; i < count; i++) { adaptedExtractMultipart(xhtml, mp.getBodyPart(i), parentPartLocal, context); } } else if (part.isMimeType("message/rfc822")) { adaptedExtractMultipart(xhtml, (Part) part.getContent(), part, context); } else if (part.isMimeType("text/html")) { if ((parentPart != null && parentPart.isMimeType(MULTIPART_ALTERNATIVE)) || (part.getDisposition() == null || !part.getDisposition().contains(Part.ATTACHMENT))) { Object data = part.getContent(); String htmlFileData = prepareString(new String(data.toString())); writeContent(part, htmlFileData, MimetypeMap.MIMETYPE_HTML, "html"); } } else if (part.isMimeType("image/*")) { String[] encoded = part.getHeader("Content-Transfer-Encoding"); if (isContained(encoded, "base64")) { if (part.getDisposition() != null && part.getDisposition().contains(Part.ATTACHMENT)) { InputStream stream = part.getInputStream(); byte[] binaryData = new byte[part.getSize()]; stream.read(binaryData, 0, part.getSize()); String encodedData = new String(Base64.encodeBase64(binaryData)); String[] split = part.getContentType().split(";"); String src = "data:" + split[0].trim() + ";base64," + encodedData; AttributesImpl attributes = new AttributesImpl(); attributes.addAttribute(null, "src", "src", "String", src); xhtml.startElement("img", attributes); xhtml.endElement("img"); } } } else { Object content = part.getContent(); if (content instanceof String) { xhtml.element("div", prepareString(part.getContent().toString())); } else if (content instanceof InputStream) { InputStream fileContent = part.getInputStream(); Parser parser = new AutoDetectParser(); Metadata attachmentMetadata = new Metadata(); BodyContentHandler handlerAttachments = new BodyContentHandler(); parser.parse(fileContent, handlerAttachments, attachmentMetadata, context); xhtml.element("div", handlerAttachments.toString()); } } }
From source file:org.alfresco.repo.content.transform.EMLParser.java
/** * Prepare extract multipart./*from w w w. j a v a2s . c o m*/ * * @param xhtml * the xhtml * @param part * the part * @param parentPart * the parent part * @param context * the context * @param attachmentList * is list with attachments to fill * @throws MessagingException * the messaging exception * @throws IOException * Signals that an I/O exception has occurred. * @throws SAXException * the sAX exception * @throws TikaException * the tika exception */ private void prepareExtractMultipart(XHTMLContentHandler xhtml, Part part, Part parentPart, ParseContext context, List<String> attachmentList) throws MessagingException, IOException, SAXException, TikaException { String disposition = part.getDisposition(); if ((disposition != null && disposition.contains(Part.ATTACHMENT))) { String fileName = part.getFileName(); if (fileName != null && fileName.startsWith("=?")) { fileName = MimeUtility.decodeText(fileName); } attachmentList.add(fileName); } String[] header = part.getHeader("Content-ID"); String key = null; if (header != null) { for (String string : header) { key = string; } } if (part.isMimeType("multipart/*")) { Multipart mp = (Multipart) part.getContent(); int count = mp.getCount(); for (int i = 0; i < count; i++) { prepareExtractMultipart(xhtml, mp.getBodyPart(i), part, context, attachmentList); } } else if (part.isMimeType(MimetypeMap.MIMETYPE_RFC822)) { prepareExtractMultipart(xhtml, (Part) part.getContent(), part, context, attachmentList); } else { if (key == null) { return; } // if ((disposition != null && disposition.contains(Part.INLINE))) { InputStream stream = part.getInputStream(); File file = new File(workingDirectory, System.currentTimeMillis() + ""); FileOutputStream fileOutputStream = new FileOutputStream(file); IOUtils.copy(stream, fileOutputStream); IOUtils.closeQuietly(fileOutputStream); String src = file.getName(); String replace = key.replace("<", "").replace(">", ""); referencesCache.put(replace, src); // } } }
From source file:org.apache.axis2.transport.mail.SimpleMailListener.java
private String getMailHeaderFromPart(Part part, String headerName) throws AxisFault { try {//from w w w .j a v a 2 s . c o m String values[] = part.getHeader(headerName); if (values != null) { return parseHeaderForQuotes(values[0]); } else { return null; } } catch (MessagingException e) { throw new AxisFault(e.getMessage(), e); } }