Example usage for javax.mail.internet MimeMessage getContent

List of usage examples for javax.mail.internet MimeMessage getContent

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage getContent.

Prototype

@Override
public Object getContent() throws IOException, MessagingException 

Source Link

Document

Return the content as a Java object.

Usage

From source file:mitm.common.security.smime.SMIMEBuilderImplTest.java

@Test
public void testEncryptDeprecatedHeaders() throws Exception {
    MimeMessage message = loadMessage("simple-text-message.eml");

    SMIMEBuilder builder = new SMIMEBuilderImpl(message, "to", "subject", "from");

    builder.setUseDeprecatedContentTypes(true);

    builder.addRecipient(encryptionCertificate, SMIMERecipientMode.ISSUER_SERIAL);

    builder.encrypt(SMIMEEncryptionAlgorithm.DES_EDE3_CBC);

    MimeMessage newMessage = builder.buildMessage();

    File file = new File(tempDir, "testEncryptDeprecatedHeaders.eml");

    FileOutputStream output = new FileOutputStream(file);

    MailUtils.writeMessage(newMessage, output);

    newMessage = MailUtils.loadMessage(file);

    assertEquals(SMIMEHeader.DEPRECATED_ENCRYPTED_CONTENT_TYPE, newMessage.getContentType());

    assertEquals(SMIMEHeader.Type.ENCRYPTED, SMIMEHeader.getSMIMEContentType(newMessage));

    assertEquals("test@example.com", newMessage.getHeader("from", ","));
    assertEquals("test@example.com", newMessage.getHeader("to", ","));
    assertEquals("test simple message", newMessage.getHeader("subject", ","));

    File opensslOutputFileSigned = new File(tempDir, "testEncryptDeprecatedHeaders-openssl.eml");

    decryptMessage(file, privateKeyEntry.getPrivateKey(), opensslOutputFileSigned);

    newMessage = MailUtils.loadMessage(opensslOutputFileSigned);

    assertEquals(SMIMEHeader.Type.NO_SMIME, SMIMEHeader.getSMIMEContentType(newMessage));

    assertTrue(newMessage.isMimeType("text/plain"));

    assertEquals("test@example.com", newMessage.getHeader("from", ","));
    assertEquals("test@example.com", newMessage.getHeader("to", ","));
    assertEquals("test simple message", newMessage.getHeader("subject", ","));

    assertEquals(SMIMEHeader.Type.NO_SMIME, SMIMEHeader.getSMIMEContentType(newMessage));

    String content = (String) newMessage.getContent();

    assertEquals("test", content.trim());
}

From source file:immf.SendMailBridge.java

/**
 * SMTP???????//from w ww  .  j  ava 2  s.  c om
 * @param msg
 * @throws IOException
 */
public void receiveMail(MyWiserMessage msg) throws IOException {
    try {
        SenderMail senderMail = new SenderMail();

        log.info("==== SMTP???????====");
        log.info("From       " + msg.getEnvelopeSender());
        log.info("Recipients  " + msg.getEnvelopeReceiver());

        MimeMessage mime = msg.getMimeMessage();

        String messageId = mime.getHeader("Message-ID", null);
        log.info("messageID  " + messageId);
        List<String> recipients;
        if (messageId != null && receivedMessageTable != null) {
            synchronized (receivedMessageTable) {
                recipients = receivedMessageTable.get(messageId);
                if (recipients != null) {
                    recipients.addAll(msg.getEnvelopeReceiver());
                    log.info("Duplicated message ignored");
                    return;
                }

                recipients = msg.getEnvelopeReceiver();
                receivedMessageTable.put(messageId, recipients);
                receivedMessageTable.wait(this.duplicationCheckTimeSec * 1000);
                receivedMessageTable.remove(messageId);
            }
        } else {
            recipients = msg.getEnvelopeReceiver();
        }

        List<InternetAddress> to = getRecipients(mime, "To");
        List<InternetAddress> cc = getRecipients(mime, "Cc");
        List<InternetAddress> bcc = getBccRecipients(recipients, to, cc);

        int maxRecipients = MaxRecipient;
        if (this.alwaysBcc != null) {
            log.debug("add alwaysbcc " + this.alwaysBcc);
            bcc.add(new InternetAddress(this.alwaysBcc));
        }
        log.info("To   " + StringUtils.join(to, " / "));
        log.info("cc   " + StringUtils.join(cc, " / "));
        log.info("bcc   " + StringUtils.join(bcc, " / "));

        senderMail.setTo(to);
        senderMail.setCc(cc);
        senderMail.setBcc(bcc);

        if (maxRecipients < (to.size() + cc.size() + bcc.size())) {
            log.warn("??????i.net???5??");
            throw new IOException("Too Much Recipients");
        }

        String contentType = mime.getContentType().toLowerCase();
        log.info("ContentType:" + contentType);

        String charset = (new ContentType(contentType)).getParameter("charset");
        log.info("charset:" + charset);

        String mailer = mime.getHeader("X-Mailer", null);
        log.info("mailer  " + mailer);

        String subject = mime.getHeader("Subject", null);
        log.info("subject  " + subject);
        if (subject != null)
            subject = this.charConv.convertSubject(subject);
        log.debug(" conv " + subject);

        if (this.useGoomojiSubject) {
            String goomojiSubject = mime.getHeader("X-Goomoji-Subject", null);
            if (goomojiSubject != null)
                subject = this.googleCharConv.convertSubject(goomojiSubject);
        }

        boolean editRe = false;
        if (this.editDocomoSubjectPrefix) {
            for (InternetAddress addr : to) {
                String[] toString = addr.getAddress().split("@", 2);
                if (subject != null && toString[1].equals("docomo.ne.jp")) {
                    editRe = true;
                }
            }
        }
        if (editRe) {
            if (subject.matches("^R[eE]: ?R[eE].*$")) {
                log.info("?subject: " + subject);
                String reCounterStr = subject.replaceAll("^R[eE]: ?R[eE](\\d*):.*$", "$1");
                int reCounter = 2;
                if (!reCounterStr.isEmpty()) {
                    reCounter = Integer.parseInt(reCounterStr);
                    reCounter++;
                }
                subject = subject.replaceAll("^R[eE]: ?R[eE]\\d*:", "Re" + Integer.toString(reCounter) + ":");
                log.info("subject: " + subject);
            }
        }

        senderMail.setSubject(subject);

        Object content = mime.getContent();
        if (content instanceof String) {
            // 
            String strContent = (String) content;
            if (contentType.toLowerCase().startsWith("text/html")) {
                log.info("Single html part " + strContent);
                strContent = this.charConv.convert(strContent, charset);
                log.debug(" conv " + strContent);
                senderMail.setHtmlContent(strContent);
            } else {
                log.info("Single plainText part " + strContent);
                strContent = this.charConv.convert(strContent, charset);
                log.debug(" conv " + strContent);
                senderMail.setPlainTextContent(strContent);
            }
        } else if (content instanceof Multipart) {
            Multipart mp = (Multipart) content;
            parseMultipart(senderMail, mp, getSubtype(contentType), null);
            if (senderMail.getHtmlContent() == null && senderMail.getHtmlWorkingContent() != null) {
                senderMail.setHtmlContent(senderMail.getHtmlWorkingContent());
            }

        } else {
            log.warn("? " + content.getClass().getName());
            throw new IOException("Unsupported type " + content.getClass().getName() + ".");
        }

        if (stripAppleQuote) {
            Util.stripAppleQuotedLines(senderMail);
        }
        Util.stripLastEmptyLines(senderMail);

        log.info("Content  " + mime.getContent());
        log.info("====");

        if (this.sendAsync) {
            // ??
            // ?????OK?
            this.picker.add(senderMail);
        } else {
            // ??????
            this.client.sendMail(senderMail, this.forcePlainText);
            if (isForwardSent) {
                status.setNeedConnect();
            }
        }

    } catch (IOException e) {
        log.warn("Bad Mail Received.", e);
        throw e;
    } catch (Exception e) {
        log.error("ReceiveMail Error.", e);
        throw new IOException("ReceiveMail Error." + e.getMessage(), e);
    }
}

From source file:mitm.application.djigzo.james.mailets.SMIMEHandlerTest.java

@Test
public void test3LayersStrictWithExplicitCertificate() throws Exception {
    SMIMEHandler mailet = new SMIMEHandler();

    mailetConfig.setInitParameter("handledProcessor", "handled");
    mailetConfig.setInitParameter("threshold", "10");
    mailetConfig.setInitParameter("strictAttribute", "attr.strict");

    mailet.init(mailetConfig);//ww w . j a v  a  2s  . co m

    MockMail mail = new MockMail();

    mail.setAttribute("attr.strict", true);

    mail.setState(Mail.TRANSPORT);

    /*
     * Make sure sub@subdomain.example.com can decrypt all
     */
    proxy.addUserCertificate("sub@subdomain.example.com", (X509Certificate) keyStore.getCertificate("NoEmail"));
    proxy.addUserCertificate("sub@subdomain.example.com",
            (X509Certificate) keyStore.getCertificate("ValidCertificate"));
    proxy.addUserCertificate("sub@subdomain.example.com",
            (X509Certificate) keyStore.getCertificate("multipleEmail"));

    /*
     * message with 3 layers of encryption
     */
    MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/3-layer-encrypted.eml"));

    mail.setMessage(message);

    Set<MailAddress> recipients = new LinkedHashSet<MailAddress>();

    recipients.add(new MailAddress("test@example.com"));
    recipients.add(new MailAddress("test2@example.com"));
    recipients.add(new MailAddress("test3@example.com"));
    recipients.add(new MailAddress("test4@example.com"));
    recipients.add(new MailAddress("sub@subdomain.example.com"));

    mail.setRecipients(recipients);

    mail.setSender(new MailAddress("sender@example.com"));

    mailet.service(mail);

    assertEquals(4, sendMailEventListener.getMails().size());

    /* message 1 */

    Mail newMail = sendMailEventListener.getMails().get(0);

    MimeMessage newMessage = newMail.getMessage();

    SMIMEInspector inspector = new SMIMEInspectorImpl(newMessage, null, "BC");

    /*
     * the last layer could not be decrypted
     */
    assertEquals(SMIMEType.ENCRYPTED, inspector.getSMIMEType());

    /*
     * Only test@example.com can decrypt the first two layers
     */
    assertEquals(1, newMail.getRecipients().size());
    assertTrue(newMail.getRecipients().contains(new MailAddress("test@example.com")));
    assertEquals("handled", newMail.getState());

    assertEquals("RC2, Key size: 128", newMessage.getHeader("X-Djigzo-Info-Encryption-Algorithm-0", ","));
    assertEquals("3DES, Key size: 168", newMessage.getHeader("X-Djigzo-Info-Encryption-Algorithm-1", ","));
    assertEquals("AES128, Key size: 128", newMessage.getHeader("X-Djigzo-Info-Encryption-Algorithm-2", ","));

    /* message 2 */

    newMail = sendMailEventListener.getMails().get(1);

    newMessage = newMail.getMessage();

    inspector = new SMIMEInspectorImpl(newMessage, null, "BC");

    /*
     * the last layer could not be decrypted
     */
    assertEquals(SMIMEType.ENCRYPTED, inspector.getSMIMEType());

    /*
     * test2@example.com and test3@example.com can only decrypt the first layers
     */
    assertEquals(2, newMail.getRecipients().size());
    assertTrue(newMail.getRecipients().contains(new MailAddress("test2@example.com")));
    assertTrue(newMail.getRecipients().contains(new MailAddress("test3@example.com")));
    assertEquals("handled", newMail.getState());

    assertEquals("RC2, Key size: 128", newMessage.getHeader("X-Djigzo-Info-Encryption-Algorithm-0", ","));
    assertEquals("3DES, Key size: 168", newMessage.getHeader("X-Djigzo-Info-Encryption-Algorithm-1", ","));
    assertNull(newMessage.getHeader("X-Djigzo-Info-Encryption-Algorithm-2"));

    /* message 3 */

    newMail = sendMailEventListener.getMails().get(2);

    newMessage = newMail.getMessage();

    inspector = new SMIMEInspectorImpl(newMessage, null, "BC");

    /*
     * the last layer was also decrypted
     */
    assertEquals(SMIMEType.NONE, inspector.getSMIMEType());

    /*
     * sub@subdomain.example.com can decrypt all layers
     */
    assertEquals(1, newMail.getRecipients().size());
    assertTrue(newMail.getRecipients().contains(new MailAddress("sub@subdomain.example.com")));
    assertEquals("handled", newMail.getState());

    assertEquals("RC2, Key size: 128", newMessage.getHeader("X-Djigzo-Info-Encryption-Algorithm-0", ","));
    assertEquals("3DES, Key size: 168", newMessage.getHeader("X-Djigzo-Info-Encryption-Algorithm-1", ","));
    assertEquals("AES128, Key size: 128", newMessage.getHeader("X-Djigzo-Info-Encryption-Algorithm-2", ","));

    assertEquals("test", ((String) newMessage.getContent()).trim());

    newMail = sendMailEventListener.getMails().get(3);

    newMessage = newMail.getMessage();

    inspector = new SMIMEInspectorImpl(newMessage, null, "BC");

    /*
     * the last layer was also decrypted
     */
    assertEquals(SMIMEType.ENCRYPTED, inspector.getSMIMEType());

    /*
     * sub@subdomain.example.com can decrypt all layers
     */
    assertEquals(1, newMail.getRecipients().size());
    assertTrue(newMail.getRecipients().contains(new MailAddress("test4@example.com")));
    assertEquals("handled", newMail.getState());

    assertEquals(Mail.GHOST, mail.getState());
}

From source file:edu.stanford.muse.email.EmailFetcherStats.java

/**
 * fetch given message idx's in given folder -- @performance critical
 *
 * @param offset - the original offset of the first message in the messages array, important to initialize
 *               for proper assignment of unique id or doc Id
 *///from   w  ww  .  j  a v a 2 s . c om
//private void fetchUncachedMessages(String sanitizedFName, Folder folder, DocCache cache, List<Integer> msgIdxs) throws MessagingException, FileNotFoundException, IOException, GeneralSecurityException {
private void fetchAndIndexMessages(Folder folder, Message[] messages, int offset, int totalMessages)
        throws MessagingException, IOException, GeneralSecurityException {
    //mark the processing of new batch
    if (offset == 0)
        fetchStartTime = System.currentTimeMillis();

    currentStatus = JSONUtils.getStatusJSON(
            (emailStore instanceof MboxEmailStore) ? "Parsing " + folder.getName() + " (can take a while)..."
                    : "Reading " + folder.getName() + "...");

    // bulk fetch of all message headers
    int n = messages.length;

    // eliminate any messages the archive already has
    messages = removeMessagesAlreadyInArchive(archive, messages);

    log.info(n - messages.length + " message(s) already in the archive");

    ArrayList<EmailDocument> emails = new ArrayList<EmailDocument>();

    // for performance, we need to do bulk prefetches, instead of fetching 1 message at a time
    // prefetchedMessages will be a temp cache of prefetched messages
    int first_i_prefetched = -1, last_i_prefetched = -1;
    List<?> prefetchedMessages = null; // the type of this can be either list<string> if text only, otherwise list<mimemmessage>

    long highestUID = archive.getLastUIDForFolder(fetchedFolderInfo.accountKey, fetchedFolderInfo.longName);
    long lastAssignedUID = highestUID;
    boolean bodyTextOnly = !fetchConfig.downloadAttachments;
    try {
        archive.openForWrite();
        for (int i = 0; i < messages.length; i++) {
            // critical step: (thanks, yourkit!)
            // null out the ref to the previous message, otherwise it stays in memory, and the heap effectively needs to be as big as the size of all messages
            if (i > 0)
                messages[i - 1] = null;

            if (isCancelled)
                break;

            Message m = messages[i];
            MimeMessage mm = (MimeMessage) m;

            if (i >= last_i_prefetched) {
                // critical perf. step: do a bulk imap prefetch
                // the prefetch will fetch as many messages as possible up to a max buffer size, and return the messages prefetched
                // last_i_prefetched tracks what is the last index into idxs that we have prefetched.
                // when we run out of prefetched messages, we do another bulk prefetch

                prefetchedMessages = do_imap_prefetch(messages, i, folder, bodyTextOnly);
                if (prefetchedMessages != null) {
                    first_i_prefetched = i;
                    last_i_prefetched = i + prefetchedMessages.size();
                }
            }

            int pctDone = ((i + offset) * 100) / totalMessages;
            long elapsedMillis = System.currentTimeMillis() - fetchStartTime;
            long unprocessedSecs = Util.getUnprocessedMessage(i + offset, totalMessages, elapsedMillis);
            int N_TEASERS = 50; // 50 ok here, because it takes a long time to fetch and process messages, so teaser computation is relatively not expensive
            int nTriesForThisMessage = 0;
            currentStatus = getStatusJSONWithTeasers(
                    "Reading " + Util.commatize(totalMessages) + " messages from " + folder.getName() + "...",
                    pctDone, elapsedMillis / 1000, unprocessedSecs, emails, N_TEASERS);

            int messageNum = mm.getMessageNumber();

            try {
                long unique_id;

                // if we have uid, that's even better
                // don't use uid's for mbox, it has a bug and always gives -1
                // see http://james.apache.org/server/rfclist/imap4/rfc2060.txt for uid spec
                if (folder instanceof UIDFolder && !(emailStore instanceof MboxEmailStore)) {
                    long uid = ((UIDFolder) folder).getUID(m);
                    unique_id = uid;
                } else
                    unique_id = lastAssignedUID + 1 + i + offset; // +1 since i starts from 0 (but lastAssignedUID can be -1 -- is that safe? -sgh)

                if (unique_id > highestUID)
                    highestUID = unique_id;

                String unique_id_as_string = Long.toString(unique_id);

                // well, we already converted to emaildoc above during removeMessagesAlreadyInArchive
                // not a serious perf. concern now, but revisit if needed
                EmailDocument ed = convertToEmailDocument(mm, unique_id_as_string); // this messageNum is mostly for debugging, it should not be used for equals etc.
                // need to check this again, because there might be duplicates such within the set we are currently processing.
                if (archive.containsDoc(ed)) {
                    stats.nMessagesAlreadyPresent++;
                    dataErrors.add("Duplicate message: " + ed); // note: report.jsp depends on this specific string
                    continue;
                }

                MimeMessage originalMessage = mm; // this is the mm that has all the headers etc.
                List<Blob> attachmentsList = new ArrayList<Blob>();

                // if we already have it prefetched, use the prefetched version
                List<String> contents = null;

                if (first_i_prefetched >= 0 && prefetchedMessages != null) {
                    if (!fetchConfig.downloadAttachments) {
                        // text only means the prefetchedMessages are stored directly as a list of strings
                        String content = (String) prefetchedMessages.get(i - first_i_prefetched); // note: this_mm only has the prefetched content, but not the headers
                        contents = new ArrayList<String>();

                        try {
                            // a special for yahoo which routinely uses quoted-printable. content looks like  =0A0D.... = etc.
                            if (mm.isMimeType("multipart/alternative")) {
                                Multipart mm_mp = (Multipart) mm.getContent();
                                Part p0 = mm_mp.getBodyPart(0);
                                if (p0 instanceof com.sun.mail.imap.IMAPBodyPart) {
                                    String encoding = ((com.sun.mail.imap.IMAPBodyPart) p0).getEncoding();
                                    if ("quoted-printable".equals(encoding)) {
                                        content = new String(
                                                Util.getBytesFromStream(javax.mail.internet.MimeUtility.decode(
                                                        new java.io.ByteArrayInputStream(content.getBytes()),
                                                        "quoted-printable")));
                                    }
                                }
                            }
                        } catch (Exception e) {
                            Util.print_exception("Error trying to parse encoding of multipart", e, log);
                        }

                        contents.add(content);
                    } else {
                        // subtle issue here: the contentType of the prefetchedMessage needs to be be set to the original_mm's content-type.
                        // this was found for cases where the original message is multipart-alternative with a text and html part.
                        // if we don't set prefetchedMessage's content type, it gets a mime type of text/plain and a body = the entire multipart including both parts.
                        // found on sgh's sent mail w/subject: "text to add in help" from  Fri, 7 Jun 2013
                        MimeMessage prefetchedMessage = (MimeMessage) prefetchedMessages
                                .get(i - first_i_prefetched);
                        String contentTypeHeaders[] = originalMessage.getHeader("Content-Type");
                        String contentTypeHeader = null;
                        if (contentTypeHeaders != null && contentTypeHeaders.length == 1)
                            contentTypeHeader = contentTypeHeaders[0];

                        if (!Util.nullOrEmpty(contentTypeHeader)) // we do care about body structure, hang on to it
                            prefetchedMessage.setHeader("Content-Type", contentTypeHeader);
                        mm = prefetchedMessage;
                    }
                    prefetchedMessages.set(i - first_i_prefetched, null); // null out to save memory
                }

                if (contents == null)
                    contents = processMessagePart(messageNum, originalMessage, mm, attachmentsList);

                // if mm is not prefetched, it is the same as original_mm
                // will also work, but will be slow as javamail accesses and fetches each mm separately, instead of using the bulk prefetched version
                // even when prefetched, the processMessagePart is somewhat expensive because the attachments have to be extracted etc.

                // we could overlap processMessagePart with do_imap_prefetch by prefetching in a separate thread, since prefetch is network limited.
                // but profiling shows processMessagePart takes only 1/4th the time of do_imap_prefetch so overlapping would be a relatively small gain.
                // not worth the effort right now.
                ed.attachments = attachmentsList;
                if (fetchConfig.downloadAttachments)
                    ed.attachmentsYetToBeDownloaded = false; // we've already downloaded our attachments

                // concat all the contents parts
                StringBuilder sb = new StringBuilder();
                for (String s : contents) {
                    sb.append(s);
                    sb.append("\n");
                }

                String contentStr = sb.toString();
                if (!messageLooksOk(contentStr)) {
                    dataErrors.add("Skipping message as it seems to have very long words: " + ed);
                    continue;
                }

                if (contentStr.length() > Config.MAX_TEXT_SIZE_TO_ANNOTATE) {
                    dataErrors.add("Skipping message as it seems to be very long: " + contentStr.length()
                            + " chars, while the max size message that will be annotated for display is "
                            + Config.MAX_TEXT_SIZE_TO_ANNOTATE + " chars. Message = " + ed);
                    // but we continue, don't skip the message entirely. See issue #111
                }

                contentStr = IndexUtils.normalizeNewlines(contentStr); // just get rid of \r's

                archive.addDoc(ed, contentStr);

                List<LinkInfo> linkList = new ArrayList<LinkInfo>();
                // linkList might be used only for slant
                IndexUtils.populateDocLinks(ed, contentStr, linkList, true);
                ed.links = linkList;
                stats.nMessagesAdded++;
            } catch (Exception ex) {
                // sometimes we get unexpected folder closed, so try again
                boolean retry = false;
                if (ex instanceof javax.mail.FolderClosedException) {
                    log.warn("Oops, thread " + threadID + " got the folder closed in its face! "
                            + ex.getMessage());

                    // sometimes we get this exception about folder closed
                    // retry up to 3 times, then give up
                    if (nTriesForThisMessage < 3) {
                        retry = true;
                        log.info("Re-opening email store; attempt #" + (nTriesForThisMessage + 1)
                                + " for message " + i);
                        nTriesForThisMessage++;
                        messages = openFolderAndGetMessages();
                        fetchHeaders(messages);
                        --i; // adjust the message index n try again
                    }
                }

                if (!retry) {
                    // we sometimes see UnsupportedEncodingException with x-utf8utf8 mime type and ParseException
                    // nothing much can be done, just create a dummy doc and add it to the cache
                    nErrors++;
                    stats.nErrors++;
                    EmailDocument ed = new EmailDocument(Integer.toString(messageNum));
                    log.warn("Exception reading message from " + folder_name() + " Message #" + messageNum + " "
                            + ex.getMessage() + "\n" + Util.stackTrace(ex));

                    ed.setErrorString(Util.stackTrace(ex));
                }
            }
        }
    } catch (Throwable t) {
        Util.print_exception(t, log);
    } finally {
        //            if (cancelled && false) // TODO: disable for now as currently only indexes are rolled back and allDocs/blobs are not rolled back in sync yet
        //               archive.rollbackIndexWrites();
        //            else
        currentStatus = JSONUtils.getStatusJSON("Saving archive...");
        archive.close();
    }

    fetchedFolderInfo.lastSeenUID = highestUID;
    log.info("at end of fetch, folder info is " + fetchedFolderInfo);

    log.info("emailfetcher thread completed, archive has " + archive.getAllDocs().size() + " docs");
}

From source file:davmail.exchange.dav.DavExchangeSession.java

/**
 * Create message in specified folder.//from w ww. j a  v  a2  s.c  om
 * 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());
    }

}

From source file:org.alfresco.module.org_alfresco_module_rm.action.impl.SplitEmailAction.java

/**
 * @see org.alfresco.repo.action.executer.ActionExecuterAbstractBase#executeImpl(org.alfresco.service.cmr.action.Action,
 *      org.alfresco.service.cmr.repository.NodeRef)
 *//*  w w w .  j a v a2  s .  c  om*/
@Override
protected void executeImpl(Action action, NodeRef actionedUponNodeRef) {
    // get node type
    getNodeService().getType(actionedUponNodeRef);

    if (logger.isDebugEnabled()) {
        logger.debug("split email:" + actionedUponNodeRef);
    }

    if (getRecordService().isRecord(actionedUponNodeRef)) {
        if (!getRecordService().isDeclared(actionedUponNodeRef)) {
            ChildAssociationRef parent = getNodeService().getPrimaryParent(actionedUponNodeRef);

            /**
             * Check whether the email message has already been split - do nothing if it has already been split
             */
            List<AssociationRef> refs = getNodeService().getTargetAssocs(actionedUponNodeRef,
                    ImapModel.ASSOC_IMAP_ATTACHMENT);
            if (refs.size() > 0) {
                if (logger.isDebugEnabled()) {
                    logger.debug("mail message has already been split - do nothing");
                }
                return;
            }

            /**
             * Get the content and if its a mime message then create atachments for each part
             */
            try {
                ContentReader reader = getContentService().getReader(actionedUponNodeRef,
                        ContentModel.PROP_CONTENT);
                InputStream is = reader.getContentInputStream();
                MimeMessage mimeMessage = new MimeMessage(null, is);
                Object content = mimeMessage.getContent();
                if (content instanceof Multipart) {
                    Multipart multipart = (Multipart) content;

                    for (int i = 0, n = multipart.getCount(); i < n; i++) {
                        Part part = multipart.getBodyPart(i);
                        if ("attachment".equalsIgnoreCase(part.getDisposition())) {
                            createAttachment(actionedUponNodeRef, parent.getParentRef(), part);
                        }
                    }
                }
            } catch (Exception e) {
                throw new AlfrescoRuntimeException(I18NUtil.getMessage(MSG_NO_READ_MIME_MESSAGE, e.toString()),
                        e);
            }
        } else {
            throw new AlfrescoRuntimeException(
                    I18NUtil.getMessage(MSG_EMAIL_DECLARED, actionedUponNodeRef.toString()));
        }
    } else {
        throw new AlfrescoRuntimeException(
                I18NUtil.getMessage(MSG_EMAIL_NOT_RECORD, actionedUponNodeRef.toString()));
    }
}

From source file:org.alfresco.repo.content.transform.EmailToPDFContentTransformer.java

/**
 * Do txt transform of eml file./* w  w w.j  a va  2 s. c om*/
 *
 * @param is
 *            the input stream
 * @param os
 *            the final output stream
 * @param inputMime
 *            the input mime type
 * @param targetMimeType
 *            the target mime type
 * @param encoding
 *            the encoding of reader
 * @param writerEncoding
 *            the writer encoding
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws TransformerConfigurationException
 *             the transformer configuration exception
 * @throws SAXException
 *             the sAX exception
 * @throws TikaException
 *             the tika exception
 * @throws MessagingException
 *             the messaging exception
 */
protected void doTxtTransform(InputStream is, OutputStream os, String inputMime, String targetMimeType,
        String encoding, String writerEncoding)
        throws IOException, TransformerConfigurationException, SAXException, TikaException, MessagingException {
    MimeMessage mimeMessage = new MimeMessage(Session.getDefaultInstance(new Properties()), is);
    final StringBuilder sb = new StringBuilder();
    Object content = mimeMessage.getContent();
    if (content instanceof Multipart) {
        Multipart multipart = (Multipart) content;
        Part part = multipart.getBodyPart(0);

        if (part.getContent() instanceof Multipart) {
            multipart = (Multipart) part.getContent();
            for (int i = 0, n = multipart.getCount(); i < n; i++) {
                part = multipart.getBodyPart(i);
                if (part.isMimeType("text/*")) {
                    sb.append(part.getContent().toString()).append("\n");

                }

            }

        } else if (part.isMimeType("text/*")) {
            sb.append(part.getContent().toString());
        }

    } else {
        sb.append(content.toString());
    }

    textToPDF(new ByteArrayInputStream(sb.toString().getBytes()), UTF_8, os);
}

From source file:org.alfresco.repo.imap.AttachmentsExtractor.java

public void extractAttachments(NodeRef messageRef, MimeMessage originalMessage)
        throws IOException, MessagingException {
    NodeRef attachmentsFolderRef = null;
    String attachmentsFolderName = null;
    boolean createFolder = false;
    switch (attachmentsExtractorMode) {
    case SAME://  w  w w  .j av a  2  s  . c  om
        attachmentsFolderRef = nodeService.getPrimaryParent(messageRef).getParentRef();
        break;
    case COMMON:
        attachmentsFolderRef = this.attachmentsFolderRef;
        break;
    case SEPARATE:
    default:
        String messageName = (String) nodeService.getProperty(messageRef, ContentModel.PROP_NAME);
        attachmentsFolderName = messageName + "-attachments";
        createFolder = true;
        break;
    }
    if (!createFolder) {
        nodeService.createAssociation(messageRef, attachmentsFolderRef,
                ImapModel.ASSOC_IMAP_ATTACHMENTS_FOLDER);
    }

    Object content = originalMessage.getContent();
    if (content instanceof Multipart) {
        Multipart multipart = (Multipart) content;

        for (int i = 0, n = multipart.getCount(); i < n; i++) {
            Part part = multipart.getBodyPart(i);
            if ("attachment".equalsIgnoreCase(part.getDisposition())) {
                if (createFolder) {
                    attachmentsFolderRef = createAttachmentFolder(messageRef, attachmentsFolderName);
                    createFolder = false;
                }
                createAttachment(messageRef, attachmentsFolderRef, part);
            }
        }
    }

}

From source file:org.alfresco.repo.imap.ImapMessageTest.java

public void testMessageModifiedBetweenReads() throws Exception {
    // Get test message UID
    final Long uid = getMessageUid(folder, 1);

    // Get unmodified message
    BODY body = getMessageBody(folder, uid);

    // Parse the multipart MIME message
    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()),
            new BufferedInputStream(body.getByteArrayInputStream()));

    // Reading first part - should be successful
    MimeMultipart content = (MimeMultipart) message.getContent();
    assertNotNull(content.getBodyPart(0).getContent());
    // Reading second part - should be successful
    assertNotNull(content.getBodyPart(1).getContent());

    // Modify message. The size of letter describing the node may change
    // These changes should be committed because it should be visible from client
    NodeRef contentNode = findNode(companyHomePathInStore + TEST_FILE);
    UserTransaction txn = transactionService.getUserTransaction();
    txn.begin();// w w w. j  a v a  2s . c o  m
    ContentWriter writer = fileFolderService.getWriter(contentNode);
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < 2000; i++) {
        sb.append("test string");
    }
    writer.putContent(sb.toString());
    txn.commit();

    // Read updated message part
    BODY bodyNew = getMessageBody(folder, uid);

    // The body should be updated
    assertFalse(Arrays.equals(bodyNew.getByteArray().getBytes(), body.getByteArray().getBytes()));

    // Parse the multipart MIME message
    message = new MimeMessage(Session.getDefaultInstance(new Properties()),
            new BufferedInputStream(bodyNew.getByteArrayInputStream()));

    // Reading first part - should be successful
    content = (MimeMultipart) message.getContent();
    assertNotNull(content.getBodyPart(0).getContent());
    // Reading second part - should be successful
    assertNotNull(content.getBodyPart(1).getContent());
}

From source file:org.alfresco.repo.imap.ImapMessageTest.java

public void testMessageRenamedBetweenReads() throws Exception {
    // Get test message UID
    final Long uid = getMessageUid(folder, 1);
    // Get Message size
    final int count = getMessageSize(folder, uid);

    // Get first part
    // Split the message into 2 part using a non multiple of 4 - 103 is a prime number
    // as the BASE64Decoder may not throw the IOException
    // see MNT-12995
    BODY body = getMessageBodyPart(folder, uid, 0, count - 103);

    // Rename message. The size of letter describing the node will change
    // These changes should be committed because it should be visible from client
    NodeRef contentNode = findNode(companyHomePathInStore + TEST_FILE);
    UserTransaction txn = transactionService.getUserTransaction();
    txn.begin();// w  w w  .  j ava2 s  .  c  om
    fileFolderService.rename(contentNode, "testtesttesttesttesttesttesttesttesttest");
    txn.commit();

    // Read second message part
    BODY bodyRest = getMessageBodyPart(folder, uid, count - 103, 103);

    // Creating and parsing message from 2 parts
    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()),
            new SequenceInputStream(new BufferedInputStream(body.getByteArrayInputStream()),
                    new BufferedInputStream(bodyRest.getByteArrayInputStream())));

    // Reading first part - should be successful
    MimeMultipart content = (MimeMultipart) message.getContent();
    assertNotNull(content.getBodyPart(0).getContent());

    try {
        // Reading second part cause error
        content.getBodyPart(1).getContent();
        fail("Should raise an IOException");
    } catch (IOException e) {
    }
}