List of usage examples for javax.mail.internet MimeUtility decodeText
public static String decodeText(String etext) throws UnsupportedEncodingException
From source file:org.alfresco.repo.imap.AttachmentsExtractor.java
/** * Create an attachment given a mime part * /*w w w .j a va 2s . c om*/ * @param messageFile the file containing the message * @param attachmentsFolderRef where to put the attachment * @param part the mime part * @throws MessagingException * @throws IOException */ private void createAttachment(NodeRef messageFile, NodeRef attachmentsFolderRef, Part part) throws MessagingException, IOException { String fileName = part.getFileName(); if (fileName == null || fileName.isEmpty()) { fileName = "unnamed"; } try { fileName = MimeUtility.decodeText(fileName); } catch (UnsupportedEncodingException e) { if (logger.isWarnEnabled()) { logger.warn("Cannot decode file name '" + fileName + "'", e); } } ContentType contentType = new ContentType(part.getContentType()); if (contentType.getBaseType().equalsIgnoreCase("application/ms-tnef")) { // The content is TNEF HMEFMessage hmef = new HMEFMessage(part.getInputStream()); // hmef.getBody(); List<org.apache.poi.hmef.Attachment> attachments = hmef.getAttachments(); for (org.apache.poi.hmef.Attachment attachment : attachments) { String subName = attachment.getLongFilename(); NodeRef attachmentNode = fileFolderService.searchSimple(attachmentsFolderRef, subName); if (attachmentNode == null) { /* * If the node with the given name does not already exist Create the content node to contain the attachment */ FileInfo createdFile = fileFolderService.create(attachmentsFolderRef, subName, ContentModel.TYPE_CONTENT); attachmentNode = createdFile.getNodeRef(); serviceRegistry.getNodeService().createAssociation(messageFile, attachmentNode, ImapModel.ASSOC_IMAP_ATTACHMENT); byte[] bytes = attachment.getContents(); ContentWriter writer = fileFolderService.getWriter(attachmentNode); // TODO ENCODING - attachment.getAttribute(TNEFProperty.); String extension = attachment.getExtension(); String mimetype = mimetypeService.getMimetype(extension); if (mimetype != null) { writer.setMimetype(mimetype); } OutputStream os = writer.getContentOutputStream(); ByteArrayInputStream is = new ByteArrayInputStream(bytes); FileCopyUtils.copy(is, os); } } } else { // not TNEF NodeRef attachmentFile = fileFolderService.searchSimple(attachmentsFolderRef, fileName); // The one possible behaviour /* * if (result.size() > 0) { for (FileInfo fi : result) { fileFolderService.delete(fi.getNodeRef()); } } */ // And another one behaviour which will overwrite the content of the existing file. It is performance preferable. if (attachmentFile == null) { FileInfo createdFile = fileFolderService.create(attachmentsFolderRef, fileName, ContentModel.TYPE_CONTENT); nodeService.createAssociation(messageFile, createdFile.getNodeRef(), ImapModel.ASSOC_IMAP_ATTACHMENT); attachmentFile = createdFile.getNodeRef(); } else { String newFileName = imapService.generateUniqueFilename(attachmentsFolderRef, fileName); FileInfo createdFile = fileFolderService.create(attachmentsFolderRef, newFileName, ContentModel.TYPE_CONTENT); nodeService.createAssociation(messageFile, createdFile.getNodeRef(), ImapModel.ASSOC_IMAP_ATTACHMENT); attachmentFile = createdFile.getNodeRef(); } nodeService.setProperty(attachmentFile, ContentModel.PROP_DESCRIPTION, nodeService.getProperty(messageFile, ContentModel.PROP_NAME)); ContentWriter writer = fileFolderService.getWriter(attachmentFile); writer.setMimetype(contentType.getBaseType()); OutputStream os = writer.getContentOutputStream(); FileCopyUtils.copy(part.getInputStream(), os); } }
From source file:org.alfresco.repo.imap.ImapMessageTest.java
public void testEncodedFromToAddresses() throws Exception { // RFC1342//from w w w . j a v a 2 s . co m String addressString = "ars.kov@gmail.com"; String personalString = "?? "; InternetAddress address = new InternetAddress(addressString, personalString, "UTF-8"); // Following method returns the address with quoted personal aka <["?? "] <ars.kov@gmail.com>> // NOTE! This should be coincided with RFC822MetadataExtracter. Would 'addresses' be quoted or not? // String decodedAddress = address.toUnicodeString(); // So, just using decode, for now String decodedAddress = MimeUtility.decodeText(address.toString()); // InternetAddress.toString(new Address[] {address}) - is used in the RFC822MetadataExtracter // So, compare with that assertFalse("Non ASCII characters in the address should be encoded", decodedAddress.equals(InternetAddress.toString(new Address[] { address }))); MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties())); MimeMessageHelper messageHelper = new MimeMessageHelper(message, false, "UTF-8"); messageHelper.setText("This is a sample message for ALF-5647"); messageHelper.setSubject("This is a sample message for ALF-5647"); messageHelper.setFrom(address); messageHelper.addTo(address); messageHelper.addCc(address); // Creating the message node in the repository String name = AlfrescoImapConst.MESSAGE_PREFIX + GUID.generate(); FileInfo messageFile = fileFolderService.create(testImapFolderNodeRef, name, ContentModel.TYPE_CONTENT); // Writing a content. new IncomingImapMessage(messageFile, serviceRegistry, message); // Getting the transformed properties from the repository // cm:originator, cm:addressee, cm:addressees, imap:messageFrom, imap:messageTo, imap:messageCc Map<QName, Serializable> properties = nodeService.getProperties(messageFile.getNodeRef()); String cmOriginator = (String) properties.get(ContentModel.PROP_ORIGINATOR); String cmAddressee = (String) properties.get(ContentModel.PROP_ADDRESSEE); @SuppressWarnings("unchecked") List<String> cmAddressees = (List<String>) properties.get(ContentModel.PROP_ADDRESSEES); String imapMessageFrom = (String) properties.get(ImapModel.PROP_MESSAGE_FROM); String imapMessageTo = (String) properties.get(ImapModel.PROP_MESSAGE_TO); String imapMessageCc = (String) properties.get(ImapModel.PROP_MESSAGE_CC); assertNotNull(cmOriginator); assertEquals(decodedAddress, cmOriginator); assertNotNull(cmAddressee); assertEquals(decodedAddress, cmAddressee); assertNotNull(cmAddressees); assertEquals(1, cmAddressees.size()); assertEquals(decodedAddress, cmAddressees.get(0)); assertNotNull(imapMessageFrom); assertEquals(decodedAddress, imapMessageFrom); assertNotNull(imapMessageTo); assertEquals(decodedAddress, imapMessageTo); assertNotNull(imapMessageCc); assertEquals(decodedAddress, imapMessageCc); }
From source file:org.apache.hupa.server.handler.GetMessageDetailsHandler.java
/** * Handle the parts of the given message. The method will call itself recursively to handle all nested parts * @param message the MimeMessage /*w w w . ja v a2 s . c o m*/ * @param con the current processing Content * @param sbPlain the StringBuffer to fill with text * @param attachmentList ArrayList with attachments * @throws UnsupportedEncodingException * @throws MessagingException * @throws IOException */ protected boolean handleParts(MimeMessage message, Object con, StringBuffer sbPlain, ArrayList<MessageAttachment> attachmentList) throws UnsupportedEncodingException, MessagingException, IOException { boolean isHTML = false; if (con instanceof String) { if (message.getContentType().toLowerCase().startsWith("text/html")) { isHTML = true; } else { isHTML = false; } sbPlain.append((String) con); } else if (con instanceof Multipart) { Multipart mp = (Multipart) con; String multipartContentType = mp.getContentType().toLowerCase(); String text = null; if (multipartContentType.startsWith("multipart/alternative")) { isHTML = handleMultiPartAlternative(mp, sbPlain); } else { for (int i = 0; i < mp.getCount(); i++) { Part part = mp.getBodyPart(i); String contentType = part.getContentType().toLowerCase(); Boolean bodyRead = sbPlain.length() > 0; if (!bodyRead && contentType.startsWith("text/plain")) { isHTML = false; text = (String) part.getContent(); } else if (!bodyRead && contentType.startsWith("text/html")) { isHTML = true; text = (String) part.getContent(); } else if (!bodyRead && contentType.startsWith("message/rfc822")) { // Extract the message and pass it MimeMessage msg = (MimeMessage) part.getDataHandler().getContent(); isHTML = handleParts(msg, msg.getContent(), sbPlain, attachmentList); } else { if (part.getFileName() != null) { // Inline images are not added to the attachment list // TODO: improve the in-line images detection if (part.getHeader("Content-ID") == null) { MessageAttachment attachment = new MessageAttachment(); attachment.setName(MimeUtility.decodeText(part.getFileName())); attachment.setContentType(part.getContentType()); attachment.setSize(part.getSize()); attachmentList.add(attachment); } } else { isHTML = handleParts(message, part.getContent(), sbPlain, attachmentList); } } } if (text != null) sbPlain.append(text); } } return isHTML; }
From source file:org.apache.hupa.server.utils.MessageUtils.java
/** * Handle the parts of the given message. The method will call itself * recursively to handle all nested parts * * @param message the MimeMessage// ww w. j ava 2s .com * @param content the current processing Content * @param sbPlain the StringBuffer to fill with text * @param attachmentList ArrayList with attachments * @throws UnsupportedEncodingException * @throws MessagingException * @throws IOException */ public static boolean handleParts(Message message, Object content, StringBuffer sbPlain, ArrayList<MessageAttachment> attachmentList) throws UnsupportedEncodingException, MessagingException, IOException { boolean isHTML = false; if (content instanceof String) { if (message.getContentType().toLowerCase().startsWith("text/html")) { isHTML = true; } else { isHTML = false; } sbPlain.append((String) content); } else if (content instanceof Multipart) { Multipart mp = (Multipart) content; String multipartContentType = mp.getContentType().toLowerCase(); String text = null; if (multipartContentType.startsWith("multipart/alternative")) { isHTML = handleMultiPartAlternative(mp, sbPlain); } else { for (int i = 0; i < mp.getCount(); i++) { Part part = mp.getBodyPart(i); String contentType = part.getContentType().toLowerCase(); Boolean bodyRead = sbPlain.length() > 0; if (!bodyRead && contentType.startsWith("text/plain")) { isHTML = false; text = (String) part.getContent(); } else if (!bodyRead && contentType.startsWith("text/html")) { isHTML = true; text = (String) part.getContent(); } else if (!bodyRead && contentType.startsWith("message/rfc822")) { // Extract the message and pass it MimeMessage msg = (MimeMessage) part.getDataHandler().getContent(); isHTML = handleParts(msg, msg.getContent(), sbPlain, attachmentList); } else { if (part.getFileName() != null) { // Inline images are not added to the attachment // list // TODO: improve the in-line images detection if (part.getHeader("Content-ID") == null) { MessageAttachment attachment = new MessageAttachmentImpl(); attachment.setName(MimeUtility.decodeText(part.getFileName())); attachment.setContentType(part.getContentType()); attachment.setSize(part.getSize()); attachmentList.add(attachment); } } else { isHTML = handleParts(message, part.getContent(), sbPlain, attachmentList); } } } if (text != null) sbPlain.append(text); } } return isHTML; }
From source file:org.apache.hupa.server.utils.MessageUtils.java
/** * Loop over MuliPart and write the content to the Outputstream if a * attachment with the given name was found. * * @param logger/* w ww.j a v a2 s.c om*/ * The logger to use * @param content * Content which should checked for attachments * @param attachmentName * The attachmentname or the unique id for the searched attachment * @throws MessagingException * @throws IOException */ public static Part handleMultiPart(Log logger, Object content, String attachmentName) throws MessagingException, IOException { if (content instanceof Multipart) { Multipart part = (Multipart) content; for (int i = 0; i < part.getCount(); i++) { Part bodyPart = part.getBodyPart(i); String fileName = bodyPart.getFileName(); String[] contentId = bodyPart.getHeader("Content-ID"); if (bodyPart.isMimeType("multipart/*")) { Part p = handleMultiPart(logger, bodyPart.getContent(), attachmentName); if (p != null) return p; } else { if (contentId != null) { for (String id : contentId) { id = id.replaceAll("^.*<(.+)>.*$", "$1"); System.out.println(attachmentName + " " + id); if (attachmentName.equals(id)) return bodyPart; } } if (fileName != null) { if (cleanName(attachmentName).equalsIgnoreCase(cleanName(MimeUtility.decodeText(fileName)))) return bodyPart; } } } } else { logger.error("Unknown content: " + content.getClass().getName()); } return null; }
From source file:org.apache.hupa.server.utils.MessageUtils.java
/** * Decode iso-xxxx strings present in subjects and emails like: * * =?ISO-8859-1?Q?No=20hay=20ma=F1ana?= <hello@hupa.org> *///w w w . j a v a2s. c o m public static String decodeText(String s) { String ret = s; try { ret = MimeUtility.decodeText(s); } catch (UnsupportedEncodingException e) { System.out.println(e.getMessage()); } ret = ret // Remove quotes around names in email addresses .replaceFirst("^[<\"' ]+([^\"<>]*)[>\"' ]+<", "$1 <"); return ret; }
From source file:org.apache.james.transport.mailets.StripAttachment.java
private boolean checkMessageRemoved(Part part, Mail mail) throws MessagingException, Exception { String fileName;// w ww .j a va 2 s . c o m fileName = part.getFileName(); // filename or name of part can be null, so we have to be careful boolean ret = false; if (fileName != null) { if (decodeFilename) fileName = MimeUtility.decodeText(fileName); if (filenameReplacingPatterns != null) fileName = new ContentReplacer(false, this).applyPatterns(filenameReplacingPatterns, fileName); if (fileNameMatches(fileName)) { if (directoryName != null) { String filename = saveAttachmentToFile(part, fileName); if (filename != null) { @SuppressWarnings("unchecked") Collection<String> c = (Collection<String>) mail .getAttribute(SAVED_ATTACHMENTS_ATTRIBUTE_KEY); if (c == null) { c = new ArrayList<String>(); mail.setAttribute(SAVED_ATTACHMENTS_ATTRIBUTE_KEY, (ArrayList<String>) c); } c.add(filename); } } if (attributeName != null) { @SuppressWarnings("unchecked") Map<String, byte[]> m = (Map<String, byte[]>) mail.getAttribute(attributeName); if (m == null) { m = new LinkedHashMap<String, byte[]>(); mail.setAttribute(attributeName, (LinkedHashMap<String, byte[]>) m); } ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); OutputStream os = new BufferedOutputStream(byteArrayOutputStream); part.writeTo(os); m.put(fileName, byteArrayOutputStream.toByteArray()); } if (removeAttachments.equals(REMOVE_MATCHED)) { ret = true; } } if (!ret) { ret = removeAttachments.equals(REMOVE_ALL); } if (ret) { @SuppressWarnings("unchecked") Collection<String> c = (Collection<String>) mail.getAttribute(REMOVED_ATTACHMENTS_ATTRIBUTE_KEY); if (c == null) { c = new ArrayList<String>(); mail.setAttribute(REMOVED_ATTACHMENTS_ATTRIBUTE_KEY, (ArrayList<String>) c); } c.add(fileName); } } return ret; }
From source file:org.apache.jmeter.protocol.mail.sampler.MailReaderSampler.java
/** * {@inheritDoc}/*w w w.jav a 2s .com*/ */ @Override public SampleResult sample(Entry e) { SampleResult parent = new SampleResult(); boolean isOK = false; // Did sample succeed? final boolean deleteMessages = getDeleteMessages(); final String serverProtocol = getServerType(); parent.setSampleLabel(getName()); String samplerString = toString(); parent.setSamplerData(samplerString); /* * Perform the sampling */ parent.sampleStart(); // Start timing try { // Create empty properties Properties props = new Properties(); if (isUseStartTLS()) { props.setProperty(mailProp(serverProtocol, "starttls.enable"), TRUE); // $NON-NLS-1$ if (isEnforceStartTLS()) { // Requires JavaMail 1.4.2+ props.setProperty(mailProp(serverProtocol, "starttls.require"), TRUE); // $NON-NLS-1$ } } if (isTrustAllCerts()) { if (isUseSSL()) { props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"), TRUST_ALL_SOCKET_FACTORY); // $NON-NLS-1$ props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$ } else if (isUseStartTLS()) { props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"), TRUST_ALL_SOCKET_FACTORY); // $NON-NLS-1$ props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$ } } else if (isUseLocalTrustStore()) { File truststore = new File(getTrustStoreToUse()); log.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath()); if (!truststore.exists()) { log.info("load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath()); truststore = new File(FileServer.getFileServer().getBaseDir(), getTrustStoreToUse()); log.info("load local truststore -Attempting to read truststore from: " + truststore.getAbsolutePath()); if (!truststore.exists()) { log.info("load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath() + ". Local truststore not available, aborting execution."); throw new IOException("Local truststore file not found. Also not available under : " + truststore.getAbsolutePath()); } } if (isUseSSL()) { // Requires JavaMail 1.4.2+ props.put(mailProp(serverProtocol, "ssl.socketFactory"), // $NON-NLS-1$ new LocalTrustStoreSSLSocketFactory(truststore)); props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$ } else if (isUseStartTLS()) { // Requires JavaMail 1.4.2+ props.put(mailProp(serverProtocol, "ssl.socketFactory"), // $NON-NLS-1$ new LocalTrustStoreSSLSocketFactory(truststore)); props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$ } } // Get session Session session = Session.getInstance(props, null); // Get the store Store store = session.getStore(serverProtocol); store.connect(getServer(), getPortAsInt(), getUserName(), getPassword()); // Get folder Folder folder = store.getFolder(getFolder()); if (deleteMessages) { folder.open(Folder.READ_WRITE); } else { folder.open(Folder.READ_ONLY); } final int messageTotal = folder.getMessageCount(); int n = getNumMessages(); if (n == ALL_MESSAGES || n > messageTotal) { n = messageTotal; } // Get directory Message[] messages = folder.getMessages(1, n); StringBuilder pdata = new StringBuilder(); pdata.append(messages.length); pdata.append(" messages found\n"); parent.setResponseData(pdata.toString(), null); parent.setDataType(SampleResult.TEXT); parent.setContentType("text/plain"); // $NON-NLS-1$ final boolean headerOnly = getHeaderOnly(); busy = true; for (Message message : messages) { StringBuilder cdata = new StringBuilder(); SampleResult child = new SampleResult(); child.sampleStart(); cdata.append("Message "); // $NON-NLS-1$ cdata.append(message.getMessageNumber()); child.setSampleLabel(cdata.toString()); child.setSamplerData(cdata.toString()); cdata.setLength(0); final String contentType = message.getContentType(); child.setContentType(contentType);// Store the content-type child.setDataEncoding(RFC_822_DEFAULT_ENCODING); // RFC 822 uses ascii per default child.setEncodingAndType(contentType);// Parse the content-type if (isStoreMimeMessage()) { // Don't save headers - they are already in the raw message ByteArrayOutputStream bout = new ByteArrayOutputStream(); message.writeTo(bout); child.setResponseData(bout.toByteArray()); // Save raw message child.setDataType(SampleResult.TEXT); } else { @SuppressWarnings("unchecked") // Javadoc for the API says this is OK Enumeration<Header> hdrs = message.getAllHeaders(); while (hdrs.hasMoreElements()) { Header hdr = hdrs.nextElement(); String value = hdr.getValue(); try { value = MimeUtility.decodeText(value); } catch (UnsupportedEncodingException uce) { // ignored } cdata.append(hdr.getName()).append(": ").append(value).append("\n"); } child.setResponseHeaders(cdata.toString()); cdata.setLength(0); if (!headerOnly) { appendMessageData(child, message); } } if (deleteMessages) { message.setFlag(Flags.Flag.DELETED, true); } child.setResponseOK(); if (child.getEndTime() == 0) {// Avoid double-call if addSubResult was called. child.sampleEnd(); } parent.addSubResult(child); } // Close connection folder.close(true); store.close(); parent.setResponseCodeOK(); parent.setResponseMessageOK(); isOK = true; } catch (NoClassDefFoundError | IOException ex) { log.debug("", ex);// No need to log normally, as we set the status parent.setResponseCode("500"); // $NON-NLS-1$ parent.setResponseMessage(ex.toString()); } catch (MessagingException ex) { log.debug("", ex);// No need to log normally, as we set the status parent.setResponseCode("500"); // $NON-NLS-1$ parent.setResponseMessage(ex.toString() + "\n" + samplerString); // $NON-NLS-1$ } finally { busy = false; } if (parent.getEndTime() == 0) {// not been set by any child samples parent.sampleEnd(); } parent.setSuccessful(isOK); return parent; }
From source file:org.elasticsearch.river.email.EmailToJson.java
public static String getSubject(MimeMessage msg) throws UnsupportedEncodingException, MessagingException { return MimeUtility.decodeText(msg.getSubject()); }
From source file:org.elasticsearch.river.email.EmailToJson.java
public static String getFrom(MimeMessage msg) throws MessagingException, UnsupportedEncodingException { String from = ""; Address[] froms = msg.getFrom();// w w w. java2s .c o m if (froms.length < 1) throw new MessagingException("?!"); InternetAddress address = (InternetAddress) froms[0]; String person = address.getPersonal(); if (person != null) { person = MimeUtility.decodeText(person) + " "; } else { person = ""; } from = person + "<" + address.getAddress() + ">"; return from; }