Example usage for javax.mail.internet MimeMessage getSentDate

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

Introduction

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

Prototype

@Override
public Date getSentDate() throws MessagingException 

Source Link

Document

Returns the value of the RFC 822 "Date" field.

Usage

From source file:fr.gouv.culture.vitam.eml.EmlExtract.java

public static String extractInfoMessage(MimeMessage message, Element root, VitamArgument argument,
        ConfigLoader config) {/*from  ww  w. j a  v a 2  s.c  o  m*/
    File oldDir = argument.currentOutputDir;
    if (argument.currentOutputDir == null) {
        if (config.outputDir != null) {
            argument.currentOutputDir = new File(config.outputDir);
        }
    }
    Element keywords = XmlDom.factory.createElement(EMAIL_FIELDS.keywords.name);
    Element metadata = XmlDom.factory.createElement(EMAIL_FIELDS.metadata.name);
    String skey = "";
    String id = config.addRankId(root);
    Address[] from = null;
    Element sub2 = null;
    try {
        from = message.getFrom();
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("From");
            if (partialResult != null && partialResult.length > 0) {
                sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.from.name);
                Element add = XmlDom.factory.createElement(EMAIL_FIELDS.fromUnit.name);
                add.setText(partialResult[0]);
                sub2.add(add);
            }
        } catch (MessagingException e) {
        }
    }
    Address sender = null;
    try {
        sender = message.getSender();
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("Sender");
            if (partialResult != null && partialResult.length > 0) {
                if (sub2 == null) {
                    sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.from.name);
                    Element add = XmlDom.factory.createElement(EMAIL_FIELDS.fromUnit.name);
                    add.setText(partialResult[0]);
                    sub2.add(add);
                }
            }
        } catch (MessagingException e) {
        }
    }
    if (from != null && from.length > 0) {
        String value0 = null;
        Element sub = (sub2 != null ? sub2 : XmlDom.factory.createElement(EMAIL_FIELDS.from.name));
        if (sender != null) {
            value0 = addAddress(sub, EMAIL_FIELDS.fromUnit.name, sender, null);
        }
        for (Address address : from) {
            addAddress(sub, EMAIL_FIELDS.fromUnit.name, address, value0);
        }
        metadata.add(sub);
    } else if (sender != null) {
        Element sub = (sub2 != null ? sub2 : XmlDom.factory.createElement(EMAIL_FIELDS.from.name));
        addAddress(sub, EMAIL_FIELDS.fromUnit.name, sender, null);
        metadata.add(sub);
    } else {
        if (sub2 != null) {
            metadata.add(sub2);
        }
    }
    Address[] replyTo = null;
    try {
        replyTo = message.getReplyTo();
        if (replyTo != null && replyTo.length > 0) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.replyTo.name);
            for (Address address : replyTo) {
                addAddress(sub, EMAIL_FIELDS.fromUnit.name, address, null);
            }
            metadata.add(sub);
        }
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("ReplyTo");
            if (partialResult != null && partialResult.length > 0) {
                sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.replyTo.name);
                addAddress(sub2, EMAIL_FIELDS.fromUnit.name, partialResult, null);
                /*Element add = XmlDom.factory.createElement(EMAIL_FIELDS.fromUnit.name);
                add.setText(partialResult[0]);
                sub2.add(add);*/
                metadata.add(sub2);
            }
        } catch (MessagingException e) {
        }
    }
    Address[] toRecipients = null;
    try {
        toRecipients = message.getRecipients(Message.RecipientType.TO);
        if (toRecipients != null && toRecipients.length > 0) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.toRecipients.name);
            for (Address address : toRecipients) {
                addAddress(sub, EMAIL_FIELDS.toUnit.name, address, null);
            }
            metadata.add(sub);
        }
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("To");
            if (partialResult != null && partialResult.length > 0) {
                sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.toRecipients.name);
                addAddress(sub2, EMAIL_FIELDS.toUnit.name, partialResult, null);
                /*for (String string : partialResult) {
                   Element add = XmlDom.factory.createElement(EMAIL_FIELDS.toUnit.name);
                   add.setText(string);
                   sub2.add(add);
                }*/
                metadata.add(sub2);
            }
        } catch (MessagingException e) {
        }
    }
    Address[] ccRecipients;
    try {
        ccRecipients = message.getRecipients(Message.RecipientType.CC);
        if (ccRecipients != null && ccRecipients.length > 0) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.ccRecipients.name);
            for (Address address : ccRecipients) {
                addAddress(sub, EMAIL_FIELDS.ccUnit.name, address, null);
            }
            metadata.add(sub);
        }
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("Cc");
            if (partialResult != null && partialResult.length > 0) {
                sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.ccRecipients.name);
                addAddress(sub2, EMAIL_FIELDS.ccUnit.name, partialResult, null);
                /*for (String string : partialResult) {
                   Element add = XmlDom.factory.createElement(EMAIL_FIELDS.ccUnit.name);
                   add.setText(string);
                   sub2.add(add);
                }*/
                metadata.add(sub2);
            }
        } catch (MessagingException e) {
        }
    }
    Address[] bccRecipients;
    try {
        bccRecipients = message.getRecipients(Message.RecipientType.BCC);
        if (bccRecipients != null && bccRecipients.length > 0) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.bccRecipients.name);
            for (Address address : bccRecipients) {
                addAddress(sub, EMAIL_FIELDS.bccUnit.name, address, null);
            }
            metadata.add(sub);
        }
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("Cc");
            if (partialResult != null && partialResult.length > 0) {
                sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.bccRecipients.name);
                addAddress(sub2, EMAIL_FIELDS.bccUnit.name, partialResult, null);
                /*for (String string : partialResult) {
                   Element add = XmlDom.factory.createElement(EMAIL_FIELDS.bccUnit.name);
                   add.setText(string);
                   sub2.add(add);
                }*/
                metadata.add(sub2);
            }
        } catch (MessagingException e) {
        }
    }
    try {
        String subject = message.getSubject();
        if (subject != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.subject.name);
            sub.setText(StringUtils.unescapeHTML(subject, true, false));
            metadata.add(sub);
        }
        Date sentDate = message.getSentDate();
        if (sentDate != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.sentDate.name);
            sub.setText(sentDate.toString());
            metadata.add(sub);
        }
        Date receivedDate = message.getReceivedDate();
        if (receivedDate != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.receivedDate.name);
            sub.setText(receivedDate.toString());
            metadata.add(sub);
        }
        String[] headers = message.getHeader("Received");
        if (headers != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.receptionTrace.name);
            MailDateFormat mailDateFormat = null;
            long maxTime = 0;
            if (receivedDate == null) {
                mailDateFormat = new MailDateFormat();
            }
            for (String string : headers) {
                Element sub3 = XmlDom.factory.createElement(EMAIL_FIELDS.trace.name);
                sub3.setText(StringUtils.unescapeHTML(string, true, false));
                sub.add(sub3);
                if (receivedDate == null) {
                    int pos = string.lastIndexOf(';');
                    if (pos > 0) {
                        String recvdate = string.substring(pos + 2).replaceAll("\t\n\r\f", "").trim();
                        try {
                            Date date = mailDateFormat.parse(recvdate);
                            if (date.getTime() > maxTime) {
                                maxTime = date.getTime();
                            }
                        } catch (ParseException e) {
                        }
                    }
                }
            }
            if (receivedDate == null) {
                Element subdate = XmlDom.factory.createElement(EMAIL_FIELDS.receivedDate.name);
                Date date = new Date(maxTime);
                subdate.setText(date.toString());
                metadata.add(subdate);
            }
            metadata.add(sub);
        }
        int internalSize = message.getSize();
        if (internalSize > 0) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.emailSize.name);
            sub.setText(Integer.toString(internalSize));
            metadata.add(sub);
        }
        String encoding = message.getEncoding();
        if (encoding != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.encoding.name);
            sub.setText(StringUtils.unescapeHTML(encoding, true, false));
            metadata.add(sub);
        }
        String description = message.getDescription();
        if (description != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.description.name);
            sub.setText(StringUtils.unescapeHTML(description, true, false));
            metadata.add(sub);
        }
        String contentType = message.getContentType();
        if (contentType != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentType.name);
            sub.setText(StringUtils.unescapeHTML(contentType, true, false));
            metadata.add(sub);
        }
        headers = message.getHeader("Content-Transfer-Encoding");
        if (headers != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentTransferEncoding.name);
            StringBuilder builder = new StringBuilder();
            for (String string : headers) {
                builder.append(StringUtils.unescapeHTML(string, true, false));
                builder.append(' ');
            }
            sub.setText(builder.toString());
            metadata.add(sub);
        }
        String[] contentLanguage = message.getContentLanguage();
        if (contentLanguage != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentLanguage.name);
            StringBuilder builder = new StringBuilder();
            for (String string : contentLanguage) {
                builder.append(StringUtils.unescapeHTML(string, true, false));
                builder.append(' ');
            }
            sub.setText(builder.toString());
            metadata.add(sub);
        }
        String contentId = message.getContentID();
        if (contentId != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentId.name);
            sub.setText(StringUtils.removeChevron(StringUtils.unescapeHTML(contentId, true, false)));
            metadata.add(sub);
        }
        String disposition = message.getDisposition();
        if (disposition != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.disposition.name);
            sub.setText(StringUtils.removeChevron(StringUtils.unescapeHTML(disposition, true, false)));
            metadata.add(sub);
        }
        headers = message.getHeader("Keywords");
        if (headers != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.msgKeywords.name);
            StringBuilder builder = new StringBuilder();
            for (String string : headers) {
                builder.append(StringUtils.unescapeHTML(string, true, false));
                builder.append(' ');
            }
            sub.setText(builder.toString());
            metadata.add(sub);
        }
        String messageId = message.getMessageID();
        if (messageId != null) {
            messageId = StringUtils.removeChevron(StringUtils.unescapeHTML(messageId, true, false)).trim();
            if (messageId.length() > 1) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.messageId.name);
                sub.setText(messageId);
                metadata.add(sub);
            }
        }
        headers = message.getHeader("In-Reply-To");
        String inreplyto = null;
        if (headers != null) {
            StringBuilder builder = new StringBuilder();
            for (String string : headers) {
                builder.append(StringUtils.removeChevron(StringUtils.unescapeHTML(string, true, false)));
                builder.append(' ');
            }
            inreplyto = builder.toString().trim();
            if (inreplyto.length() > 0) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.inReplyTo.name);
                sub.setText(inreplyto);
                if (messageId != null && messageId.length() > 1) {
                    String old = filEmls.get(inreplyto);
                    if (old == null) {
                        old = messageId;
                    } else {
                        old += "," + messageId;
                    }
                    filEmls.put(inreplyto, old);
                }
                metadata.add(sub);
            }
        }
        headers = message.getHeader("References");
        if (headers != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.references.name);
            StringBuilder builder = new StringBuilder();
            for (String string : headers) {
                builder.append(StringUtils.removeChevron(StringUtils.unescapeHTML(string, true, false)));
                builder.append(' ');
            }
            String[] refs = builder.toString().trim().split(" ");
            for (String string : refs) {
                if (string.length() > 0) {
                    Element ref = XmlDom.factory.createElement(EMAIL_FIELDS.reference.name);
                    ref.setText(string);
                    sub.add(ref);
                }
            }
            metadata.add(sub);
        }
        Element prop = XmlDom.factory.createElement(EMAIL_FIELDS.properties.name);
        headers = message.getHeader("X-Priority");
        if (headers == null) {
            headers = message.getHeader("Priority");
            if (headers != null && headers.length > 0) {
                prop.addAttribute(EMAIL_FIELDS.priority.name, headers[0]);
            }
        } else if (headers != null && headers.length > 0) {
            String imp = headers[0];
            try {
                int Priority = Integer.parseInt(imp);
                switch (Priority) {
                case 5:
                    imp = "LOWEST";
                    break;
                case 4:
                    imp = "LOW";
                    break;
                case 3:
                    imp = "NORMAL";
                    break;
                case 2:
                    imp = "HIGH";
                    break;
                case 1:
                    imp = "HIGHEST";
                    break;
                default:
                    imp = "LEV" + Priority;
                }
            } catch (NumberFormatException e) {
                // ignore since imp will be used as returned
            }
            prop.addAttribute(EMAIL_FIELDS.priority.name, imp);
        }
        headers = message.getHeader("Sensitivity");
        if (headers != null && headers.length > 0) {
            prop.addAttribute(EMAIL_FIELDS.sensitivity.name, headers[0]);
        }
        headers = message.getHeader("X-RDF");
        if (headers != null && headers.length > 0) {
            System.err.println("Found X-RDF");
            StringBuilder builder = new StringBuilder();
            for (String string : headers) {
                builder.append(string);
                builder.append("\n");
            }
            try {
                byte[] decoded = org.apache.commons.codec.binary.Base64.decodeBase64(builder.toString());
                String rdf = new String(decoded);
                Document tempDocument = DocumentHelper.parseText(rdf);
                Element xrdf = prop.addElement("x-rdf");
                xrdf.add(tempDocument.getRootElement());
            } catch (Exception e) {
                System.err.println("Cannot decode X-RDF: " + e.getMessage());
            }
        }
        try {
            File old = argument.currentOutputDir;
            if (config.extractFile) {
                File newOutDir = new File(argument.currentOutputDir, id);
                newOutDir.mkdirs();
                argument.currentOutputDir = newOutDir;
            }
            if (argument.extractKeyword) {
                skey = handleMessage(message, metadata, prop, id, argument, config);
                // should have hasAttachment
                if (prop.hasContent()) {
                    metadata.add(prop);
                }
                if (metadata.hasContent()) {
                    root.add(metadata);
                }
                ExtractInfo.exportMetadata(keywords, skey, "", config, null);
                if (keywords.hasContent()) {
                    root.add(keywords);
                }
            } else {
                handleMessage(message, metadata, prop, id, argument, config);
                // should have hasAttachment
                if (prop.hasContent()) {
                    metadata.add(prop);
                }
                if (metadata.hasContent()) {
                    root.add(metadata);
                }
            }
            argument.currentOutputDir = old;
        } catch (IOException e) {
            System.err.println(StaticValues.LBL.error_error.get() + e.toString());
        }
        try {
            message.getInputStream().close();
        } catch (IOException e) {
            System.err.println(StaticValues.LBL.error_error.get() + e.toString());
        }
        root.addAttribute(EMAIL_FIELDS.status.name, "ok");
    } catch (MessagingException e) {
        System.err.println(StaticValues.LBL.error_error.get() + e.toString());
        e.printStackTrace();
        String status = "Error during identification";
        root.addAttribute(EMAIL_FIELDS.status.name, status);
    } catch (Exception e) {
        System.err.println(StaticValues.LBL.error_error.get() + e.toString());
        e.printStackTrace();
        String status = "Error during identification";
        root.addAttribute(EMAIL_FIELDS.status.name, status);
    }
    argument.currentOutputDir = oldDir;
    return skey;
}

From source file:com.zimbra.cs.service.mail.ToXML.java

/** Encodes a Message object into <m> element with <mp> elements for
 *  message body.//  www  .  j a v a2s  .co  m
 * @param parent  The Element to add the new <tt>&lt;m></tt> to.
 * @param ifmt    The formatter to sue when serializing item ids.
 * @param msg     The Message to serialize.
 * @param part    If non-null, serialize this message/rfc822 subpart of
 *                the Message instead of the Message itself.
 * @param maxSize TODO
 * @param wantHTML  <tt>true</tt> to prefer HTML parts as the "body",
 *                  <tt>false</tt> to prefer text/plain parts.
 * @param neuter  Whether to rename "src" attributes on HTML <img> tags.
 * @param headers Extra message headers to include in the returned element.
 * @param serializeType If <tt>false</tt>, always serializes as an
 *                      <tt>&lt;m></tt> element.
 * @param bestEffort  If <tt>true</tt>, errors serializing part content
 *                    are swallowed.
 * @return The newly-created <tt>&lt;m></tt> Element, which has already
 *         been added as a child to the passed-in <tt>parent</tt>.
 * @throws ServiceException */
private static Element encodeMessageAsMP(Element parent, ItemIdFormatter ifmt, OperationContext octxt,
        Message msg, String part, int maxSize, boolean wantHTML, boolean neuter, Set<String> headers,
        boolean serializeType, boolean wantExpandGroupInfo, boolean bestEffort, boolean encodeMissingBlobs,
        MsgContent wantContent) throws ServiceException {
    Element m = null;
    boolean success = false;
    try {
        boolean wholeMessage = part == null || part.trim().isEmpty();
        if (wholeMessage) {
            m = encodeMessageCommon(parent, ifmt, octxt, msg, NOTIFY_FIELDS, serializeType);
            m.addAttribute(MailConstants.A_ID, ifmt.formatItemId(msg));
        } else {
            m = parent.addElement(MailConstants.E_MSG);
            m.addAttribute(MailConstants.A_ID, ifmt.formatItemId(msg));
            m.addAttribute(MailConstants.A_PART, part);
        }

        MimeMessage mm = null;
        try {
            String requestedAccountId = octxt.getmRequestedAccountId();
            String authtokenAccountId = octxt.getmAuthTokenAccountId();
            boolean isDecryptionNotAllowed = StringUtils.isNotEmpty(authtokenAccountId)
                    && !authtokenAccountId.equalsIgnoreCase(requestedAccountId);
            if (isDecryptionNotAllowed && Mime.isEncrypted(msg.getMimeMessage(false).getContentType())) {
                mm = msg.getMimeMessage(false);
            } else {
                mm = msg.getMimeMessage();
            }
        } catch (MailServiceException e) {
            if (encodeMissingBlobs && MailServiceException.NO_SUCH_BLOB.equals(e.getCode())) {
                ZimbraLog.mailbox.error("Unable to get blob while encoding message", e);
                encodeEmail(m, msg.getSender(), EmailType.FROM);
                encodeEmail(m, msg.getSender(), EmailType.SENDER);
                if (msg.getRecipients() != null) {
                    addEmails(m, Mime.parseAddressHeader(msg.getRecipients()), EmailType.TO);
                }
                m.addAttribute(MailConstants.A_SUBJECT, msg.getSubject());
                Element mimePart = m.addElement(MailConstants.E_MIMEPART);
                mimePart.addAttribute(MailConstants.A_PART, 1);
                mimePart.addAttribute(MailConstants.A_BODY, true);
                mimePart.addAttribute(MailConstants.A_CONTENT_TYPE, MimeConstants.CT_TEXT_PLAIN);

                String errMsg = L10nUtil.getMessage(L10nUtil.MsgKey.errMissingBlob,
                        msg.getAccount().getLocale(), ifmt.formatItemId(msg));
                m.addAttribute(MailConstants.E_FRAG, errMsg, Element.Disposition.CONTENT);
                mimePart.addAttribute(MailConstants.E_CONTENT, errMsg, Element.Disposition.CONTENT);
                success = true; //not really success, but mark as such so the element is appended correctly
                return m;
            }
            throw e;
        }
        if (!wholeMessage) {
            MimePart mp = Mime.getMimePart(mm, part);
            if (mp == null) {
                throw MailServiceException.NO_SUCH_PART(part);
            }
            Object content = Mime.getMessageContent(mp);
            if (!(content instanceof MimeMessage)) {
                throw MailServiceException.NO_SUCH_PART(part);
            }
            mm = (MimeMessage) content;
        } else {
            part = "";
        }

        // Add fragment before emails to maintain consistent ordering
        // of elements with encodeConversation - need to do this to
        // overcome JAXB issues.

        String fragment = msg.getFragment();
        if (fragment != null && !fragment.isEmpty()) {
            m.addAttribute(MailConstants.E_FRAG, fragment, Element.Disposition.CONTENT);
        }

        addEmails(m, Mime.parseAddressHeader(mm, "From"), EmailType.FROM);
        addEmails(m, Mime.parseAddressHeader(mm, "Sender"), EmailType.SENDER);
        addEmails(m, Mime.parseAddressHeader(mm, "Reply-To"), EmailType.REPLY_TO);
        addEmails(m, Mime.parseAddressHeader(mm, "To"), EmailType.TO);
        addEmails(m, Mime.parseAddressHeader(mm, "Cc"), EmailType.CC);
        addEmails(m, Mime.parseAddressHeader(mm, "Bcc"), EmailType.BCC);
        addEmails(m, Mime.parseAddressHeader(mm.getHeader("Resent-From", null), false), EmailType.RESENT_FROM);
        // read-receipts only get sent by the mailbox's owner
        if (!(octxt.isDelegatedRequest(msg.getMailbox()) && octxt.isOnBehalfOfRequest(msg.getMailbox()))) {
            addEmails(m, Mime.parseAddressHeader(mm, "Disposition-Notification-To"), EmailType.READ_RECEIPT);
        }

        String calIntendedFor = msg.getCalendarIntendedFor();
        m.addAttribute(MailConstants.A_CAL_INTENDED_FOR, calIntendedFor);

        String subject = Mime.getSubject(mm);
        if (subject != null) {
            m.addAttribute(MailConstants.E_SUBJECT, StringUtil.stripControlCharacters(subject),
                    Element.Disposition.CONTENT);
        }

        String messageID = mm.getMessageID();
        if (messageID != null && !messageID.trim().isEmpty()) {
            m.addAttribute(MailConstants.E_MSG_ID_HDR, StringUtil.stripControlCharacters(messageID),
                    Element.Disposition.CONTENT);
        }

        if (wholeMessage && msg.isDraft()) {
            if (!msg.getDraftOrigId().isEmpty()) {
                ItemId origId = new ItemId(msg.getDraftOrigId(), msg.getMailbox().getAccountId());
                m.addAttribute(MailConstants.A_ORIG_ID, ifmt.formatItemId(origId));
            }
            if (!msg.getDraftReplyType().isEmpty()) {
                m.addAttribute(MailConstants.A_REPLY_TYPE, msg.getDraftReplyType());
            }
            if (!msg.getDraftIdentityId().isEmpty()) {
                m.addAttribute(MailConstants.A_IDENTITY_ID, msg.getDraftIdentityId());
            }
            if (!msg.getDraftAccountId().isEmpty()) {
                m.addAttribute(MailConstants.A_FOR_ACCOUNT, msg.getDraftAccountId());
            }
            String inReplyTo = mm.getHeader("In-Reply-To", null);
            if (inReplyTo != null && !inReplyTo.isEmpty()) {
                m.addAttribute(MailConstants.E_IN_REPLY_TO, StringUtil.stripControlCharacters(inReplyTo),
                        Element.Disposition.CONTENT);
            }
            if (msg.getDraftAutoSendTime() != 0) {
                m.addAttribute(MailConstants.A_AUTO_SEND_TIME, msg.getDraftAutoSendTime());
            }
        }

        if (!wholeMessage) {
            m.addAttribute(MailConstants.A_SIZE, mm.getSize());
        }

        Date sent = mm.getSentDate();
        if (sent != null) {
            m.addAttribute(MailConstants.A_SENT_DATE, sent.getTime());
        }

        Calendar resent = DateUtil.parseRFC2822DateAsCalendar(mm.getHeader("Resent-Date", null));
        if (resent != null) {
            m.addAttribute(MailConstants.A_RESENT_DATE, resent.getTimeInMillis());
        }

        if (msg.isInvite() && msg.hasCalendarItemInfos()) {
            encodeInvitesForMessage(m, ifmt, octxt, msg, NOTIFY_FIELDS, neuter);
        }

        if (headers != null) {
            for (String name : headers) {
                String[] values = mm.getHeader(name);
                if (values != null) {
                    for (int i = 0; i < values.length; i++) {
                        m.addKeyValuePair(name, values[i], MailConstants.A_HEADER,
                                MailConstants.A_ATTRIBUTE_NAME);
                    }
                }
            }
        }

        List<MPartInfo> parts = Mime.getParts(mm, getDefaultCharset(msg));
        if (parts != null && !parts.isEmpty()) {
            Set<MPartInfo> bodies = Mime.getBody(parts, wantHTML);
            addParts(m, parts.get(0), bodies, part, maxSize, neuter, false, getDefaultCharset(msg), bestEffort,
                    wantContent);
        }

        if (wantExpandGroupInfo) {
            ZimbraLog.gal.trace("want expand group info");
            Account authedAcct = octxt.getAuthenticatedUser();
            Account requestedAcct = msg.getMailbox().getAccount();
            encodeAddrsWithGroupInfo(m, requestedAcct, authedAcct);
        } else {
            ZimbraLog.gal.trace("do not want expand group info");
        }

        success = true;
        // update crypto flags - isSigned/isEncrypted
        if (SmimeHandler.getHandler() != null) {
            if (!wholeMessage) {
                // check content type of attachment message for encryption flag
                SmimeHandler.getHandler().updateCryptoFlags(msg, m, mm, mm);
            } else {
                MimeMessage originalMimeMessage = msg.getMimeMessage(false);
                SmimeHandler.getHandler().updateCryptoFlags(msg, m, originalMimeMessage, mm);
            }
        }

        // if the mime it is signed
        if (Mime.isMultipartSigned(mm.getContentType()) || Mime.isPKCS7Signed(mm.getContentType())) {
            ZimbraLog.mailbox
                    .debug("The message is signed. Forwarding it to SmimeHandler for signature verification.");
            if (SmimeHandler.getHandler() != null) {
                SmimeHandler.getHandler().verifyMessageSignature(msg.getMailbox().getAccount(), m, mm,
                        octxt.getmResponseProtocol());
            }
        } else {
            // if the original mime message was PKCS7-signed and it was
            // decoded and stored in cache as plain mime
            if ((mm instanceof Mime.FixedMimeMessage) && ((Mime.FixedMimeMessage) mm).isPKCS7Signed()) {
                if (SmimeHandler.getHandler() != null) {
                    SmimeHandler.getHandler().addPKCS7SignedMessageSignatureDetails(
                            msg.getMailbox().getAccount(), m, mm, octxt.getmResponseProtocol());
                }
            }
        }
        return m;
    } catch (IOException ex) {
        throw ServiceException.FAILURE(ex.getMessage(), ex);
    } catch (MessagingException ex) {
        throw ServiceException.FAILURE(ex.getMessage(), ex);
    } finally {
        // don't leave turds around if we're going to retry
        if (!success && !bestEffort && m != null) {
            m.detach();
        }
    }
}

From source file:net.wastl.webmail.server.WebMailSession.java

/**
 * Fetch a message from a folder.//from   w  w  w  . ja  v a  2  s .  c o m
 * Will put the messages parameters in the sessions environment
 *
 * @param foldername Name of the folder were the message should be fetched from
 * @param msgnum Number of the message to fetch
 * @param mode there are three different modes: standard, reply and forward. reply and forward will enter the message
 *             into the current work element of the user and set some additional flags on the message if the user
 *             has enabled this option.
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_STANDARD
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_REPLY
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_FORWARD
 */
public void getMessage(String folderhash, int msgnum, int mode) throws NoSuchFolderException, WebMailException {
    // security reasons:
    // attachments=null;

    try {
        TimeZone tz = TimeZone.getDefault();
        DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT,
                user.getPreferredLocale());
        df.setTimeZone(tz);
        Folder folder = getFolder(folderhash);
        Element xml_folder = model.getFolder(folderhash);

        if (folder == null) {
            throw new NoSuchFolderException("No such folder: " + folderhash);
        }

        if (folder.isOpen() && folder.getMode() == Folder.READ_WRITE) {
            folder.close(false);
            folder.open(Folder.READ_ONLY);
        } else if (!folder.isOpen()) {
            folder.open(Folder.READ_ONLY);
        }

        MimeMessage m = (MimeMessage) folder.getMessage(msgnum);

        String messageid;
        try {
            StringTokenizer tok = new StringTokenizer(m.getMessageID(), "<>");
            messageid = tok.nextToken();
        } catch (NullPointerException ex) {
            // For mail servers that don't generate a Message-ID (Outlook et al)
            messageid = user.getLogin() + "." + msgnum + ".jwebmail@" + user.getDomain();
        }

        Element xml_current = model.setCurrentMessage(messageid);
        XMLMessage xml_message = model.getMessage(xml_folder, m.getMessageNumber() + "", messageid);

        /* Check whether we already cached this message (not only headers but complete)*/
        boolean cached = xml_message.messageCompletelyCached();
        /* If we cached the message, we don't need to fetch it again */
        if (!cached) {
            //Element xml_header=model.getHeader(xml_message);

            try {
                String from = MimeUtility.decodeText(Helper.joinAddress(m.getFrom()));
                String replyto = MimeUtility.decodeText(Helper.joinAddress(m.getReplyTo()));
                String to = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.TO)));
                String cc = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.CC)));
                String bcc = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.BCC)));
                Date date_orig = m.getSentDate();
                String date = getStringResource("no date");
                if (date_orig != null) {
                    date = df.format(date_orig);
                }
                String subject = "";
                if (m.getSubject() != null) {
                    subject = MimeUtility.decodeText(m.getSubject());
                }
                if (subject == null || subject.equals("")) {
                    subject = getStringResource("no subject");
                }

                try {
                    Flags.Flag[] sf = m.getFlags().getSystemFlags();
                    for (int j = 0; j < sf.length; j++) {
                        if (sf[j] == Flags.Flag.RECENT)
                            xml_message.setAttribute("recent", "true");
                        if (sf[j] == Flags.Flag.SEEN)
                            xml_message.setAttribute("seen", "true");
                        if (sf[j] == Flags.Flag.DELETED)
                            xml_message.setAttribute("deleted", "true");
                        if (sf[j] == Flags.Flag.ANSWERED)
                            xml_message.setAttribute("answered", "true");
                        if (sf[j] == Flags.Flag.DRAFT)
                            xml_message.setAttribute("draft", "true");
                        if (sf[j] == Flags.Flag.FLAGGED)
                            xml_message.setAttribute("flagged", "true");
                        if (sf[j] == Flags.Flag.USER)
                            xml_message.setAttribute("user", "true");
                    }
                } catch (NullPointerException ex) {
                }
                if (m.getContentType().toUpperCase().startsWith("MULTIPART/")) {
                    xml_message.setAttribute("attachment", "true");
                }

                int size = m.getSize();
                size /= 1024;
                xml_message.setAttribute("size", (size > 0 ? size + "" : "<1") + " kB");

                /* Set all of what we found into the DOM */
                xml_message.setHeader("FROM", from);
                xml_message.setHeader("SUBJECT", Fancyfier.apply(subject));
                xml_message.setHeader("TO", to);
                xml_message.setHeader("CC", cc);
                xml_message.setHeader("BCC", bcc);
                xml_message.setHeader("REPLY-TO", replyto);
                xml_message.setHeader("DATE", date);

                /* Decode MIME contents recursively */
                xml_message.removeAllParts();
                parseMIMEContent(m, xml_message, messageid);

            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding in parseMIMEContent: " + e.getMessage());
            }
        }
        /* Set seen flag (Maybe make that threaded to improve performance) */
        if (user.wantsSetFlags()) {
            if (folder.isOpen() && folder.getMode() == Folder.READ_ONLY) {
                folder.close(false);
                folder.open(Folder.READ_WRITE);
            } else if (!folder.isOpen()) {
                folder.open(Folder.READ_WRITE);
            }
            folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.SEEN), true);
            folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.RECENT), false);
            if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) {
                folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.ANSWERED), true);
            }
        }
        folder.close(false);

        /* In this part we determine whether the message was requested so that it may be used for
           further editing (replying or forwarding). In this case we set the current "work" message to the
           message we just fetched and then modifiy it a little (quote, add a "Re" to the subject, etc). */
        XMLMessage work = null;
        if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY
                || (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) {
            log.debug("Setting work message!");
            work = model.setWorkMessage(xml_message);

            String newmsgid = WebMailServer.generateMessageID(user.getUserName());

            if (work != null && (mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) {
                String from = work.getHeader("FROM");
                work.setHeader("FROM", user.getDefaultEmail());
                work.setHeader("TO", from);
                work.prepareReply(getStringResource("reply subject prefix"),
                        getStringResource("reply subject postfix"), getStringResource("reply message prefix"),
                        getStringResource("reply message postfix"));

            } else if (work != null && (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) {
                String from = work.getHeader("FROM");
                work.setHeader("FROM", user.getDefaultEmail());
                work.setHeader("TO", "");
                work.setHeader("CC", "");
                work.prepareForward(getStringResource("forward subject prefix"),
                        getStringResource("forward subject postfix"),
                        getStringResource("forward message prefix"),
                        getStringResource("forward message postfix"));

                /* Copy all references to MIME parts to the new message id */
                for (String key : getMimeParts(work.getAttribute("msgid"))) {
                    StringTokenizer tok2 = new StringTokenizer(key, "/");
                    tok2.nextToken();
                    String newkey = tok2.nextToken();
                    mime_parts_decoded.put(newmsgid + "/" + newkey, mime_parts_decoded.get(key));
                }
            }

            /* Clear the msgnr and msgid fields at last */
            work.setAttribute("msgnr", "0");
            work.setAttribute("msgid", newmsgid);
            prepareCompose();
        }
    } catch (MessagingException ex) {
        log.error("Failed to get message.  Doing nothing instead.", ex);
    }
}

From source file:org.alfresco.email.server.impl.subetha.SubethaEmailMessage.java

private void processMimeMessage(MimeMessage mimeMessage) {
    if (from == null) {
        Address[] addresses = null;//  w w  w.ja  v  a 2s  .  co m
        try {
            addresses = mimeMessage.getFrom();
        } catch (MessagingException e) {
            throw new EmailMessageException(ERR_EXTRACTING_FROM_ADDRESS, e.getMessage());
        }
        if (addresses == null || addresses.length == 0) {
            //throw new EmailMessageException(ERR_NO_FROM_ADDRESS);
        } else {
            if (addresses[0] instanceof InternetAddress) {
                from = ((InternetAddress) addresses[0]).getAddress();
            } else {
                from = addresses[0].toString();
            }
        }
    }

    if (to == null) {
        Address[] addresses = null;
        try {
            addresses = mimeMessage.getAllRecipients();
        } catch (MessagingException e) {
            throw new EmailMessageException(ERR_EXTRACTING_TO_ADDRESS, e.getMessage());
        }
        if (addresses == null || addresses.length == 0) {
            //throw new EmailMessageException(ERR_NO_TO_ADDRESS);
        } else {
            if (addresses[0] instanceof InternetAddress) {
                to = ((InternetAddress) addresses[0]).getAddress();
            } else {
                to = addresses[0].toString();
            }
        }
    }

    if (cc == null) {
        try {
            ArrayList<String> list = new ArrayList<String>();

            Address[] cca = mimeMessage.getRecipients(RecipientType.CC);

            if (cca != null) {
                for (Address a : cca) {
                    list.add(a.toString());
                }
            }
            cc = list;
        } catch (MessagingException e) {
            // Do nothing - this is not a show-stopper.
            cc = null;
        }
    }

    try {
        subject = mimeMessage.getSubject();
        //subject = encodeSubject(mimeMessage.getSubject());
    } catch (MessagingException e) {
        throw new EmailMessageException(ERR_EXTRACTING_SUBJECT, e.getMessage());
    }
    //if (subject == null)
    //{
    //    subject = ""; // Just anti-null stub :)
    //}

    try {
        sentDate = mimeMessage.getSentDate();
    } catch (MessagingException e) {
        throw new EmailMessageException(ERR_EXTRACTING_SENT_DATE, e.getMessage());
    }
    if (sentDate == null) {
        sentDate = new Date(); // Just anti-null stub :)
    }

    parseMessagePart(mimeMessage);
    attachments = new EmailMessagePart[attachmentList.size()];
    attachmentList.toArray(attachments);
    attachmentList = null;
}

From source file:org.alfresco.repo.invitation.AbstractInvitationServiceImplTest.java

/**
 * Test nominated user - new user//from   w w w  .j av  a  2s  .  com
 * 
 * @throws Exception
 */
public void testNominatedInvitationNewUser() throws Exception {
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.SECOND, -1);
    Date startDate = calendar.getTime();

    String inviteeFirstName = PERSON_FIRSTNAME;
    String inviteeLastName = PERSON_LASTNAME;
    String inviteeEmail = "123@alfrescotesting.com";
    String inviteeUserName = null;
    Invitation.ResourceType resourceType = Invitation.ResourceType.WEB_SITE;
    String resourceName = SITE_SHORT_NAME_INVITE;
    String inviteeRole = SiteModel.SITE_COLLABORATOR;
    String serverPath = "wibble";
    String acceptUrl = "froob";
    String rejectUrl = "marshmallow";

    this.authenticationComponent.setCurrentUser(USER_MANAGER);

    NominatedInvitation nominatedInvitation = invitationService.inviteNominated(inviteeFirstName,
            inviteeLastName, inviteeEmail, resourceType, resourceName, inviteeRole, serverPath, acceptUrl,
            rejectUrl);

    assertNotNull("nominated invitation is null", nominatedInvitation);
    String inviteId = nominatedInvitation.getInviteId();
    assertEquals("first name wrong", inviteeFirstName, nominatedInvitation.getInviteeFirstName());
    assertEquals("last name wrong", inviteeLastName, nominatedInvitation.getInviteeLastName());
    assertEquals("email name wrong", inviteeEmail, nominatedInvitation.getInviteeEmail());

    // Generated User Name should be returned
    inviteeUserName = nominatedInvitation.getInviteeUserName();
    assertNotNull("generated user name is null", inviteeUserName);
    // sentInviteDate should be set to today
    {
        Date sentDate = nominatedInvitation.getSentInviteDate();
        assertTrue("sentDate wrong - too early. Start Date: " + startDate + "\nSent Date: " + sentDate,
                sentDate.after(startDate));
        assertTrue("sentDate wrong - too lateStart Date: " + startDate + "\nSent Date: " + sentDate,
                sentDate.before(new Date(new Date().getTime() + 1)));
    }

    assertEquals("resource type name wrong", resourceType, nominatedInvitation.getResourceType());
    assertEquals("resource name wrong", resourceName, nominatedInvitation.getResourceName());
    assertEquals("role  name wrong", inviteeRole, nominatedInvitation.getRoleName());
    assertEquals("server path wrong", serverPath, nominatedInvitation.getServerPath());
    assertEquals("accept URL wrong", acceptUrl, nominatedInvitation.getAcceptUrl());
    assertEquals("reject URL wrong", rejectUrl, nominatedInvitation.getRejectUrl());

    /**
     * Now we have an invitation get it and check the details have been
     * returned correctly.
     */
    {
        NominatedInvitation invitation = (NominatedInvitation) invitationService.getInvitation(inviteId);

        assertNotNull("invitation is null", invitation);
        assertEquals("invite id wrong", inviteId, invitation.getInviteId());
        assertEquals("first name wrong", inviteeFirstName, invitation.getInviteeFirstName());
        assertEquals("last name wrong", inviteeLastName, invitation.getInviteeLastName());
        assertEquals("user name wrong", inviteeUserName, invitation.getInviteeUserName());
        assertEquals("resource type name wrong", resourceType, invitation.getResourceType());
        assertEquals("resource name wrong", resourceName, invitation.getResourceName());
        assertEquals("role  name wrong", inviteeRole, invitation.getRoleName());
        assertEquals("server path wrong", serverPath, invitation.getServerPath());
        assertEquals("accept URL wrong", acceptUrl, invitation.getAcceptUrl());
        assertEquals("reject URL wrong", rejectUrl, invitation.getRejectUrl());

        Date sentDate = invitation.getSentInviteDate();
        // sentInviteDate should be set to today
        assertTrue("sentDate wrong too early", sentDate.after(startDate));
        assertTrue("sentDate wrong - too late", sentDate.before(new Date(new Date().getTime() + 1)));
    }

    /**
     * Check the email itself, and check it
     *  is as we would expect it to be
     */
    {
        MimeMessage msg = mailService.retrieveLastTestMessage();

        assertEquals(1, msg.getAllRecipients().length);
        assertEquals(inviteeEmail, msg.getAllRecipients()[0].toString());

        assertEquals(1, msg.getFrom().length);
        assertEquals(USER_MANAGER + "@alfrescotesting.com", msg.getFrom()[0].toString());

        // Hasn't been sent, so no sent or received date
        assertNull("Not been sent yet", msg.getSentDate());
        assertNull("Not been sent yet", msg.getReceivedDate());

        // TODO - check some more details of the email
        assertTrue((msg.getSubject().indexOf("You have been invited to join the") != -1));
    }

    /**
     * Search for the new invitation
     */
    List<Invitation> invitations = invitationService.listPendingInvitationsForResource(resourceType,
            resourceName);
    assertTrue("invitations is empty", !invitations.isEmpty());

    NominatedInvitation firstInvite = (NominatedInvitation) invitations.get(0);
    assertEquals("invite id wrong", inviteId, firstInvite.getInviteId());
    assertEquals("first name wrong", inviteeFirstName, firstInvite.getInviteeFirstName());
    assertEquals("last name wrong", inviteeLastName, firstInvite.getInviteeLastName());
    assertEquals("user name wrong", inviteeUserName, firstInvite.getInviteeUserName());

    /**
     * Now accept the invitation
     */
    NominatedInvitation acceptedInvitation = (NominatedInvitation) invitationService
            .accept(firstInvite.getInviteId(), firstInvite.getTicket());
    assertEquals("invite id wrong", firstInvite.getInviteId(), acceptedInvitation.getInviteId());
    assertEquals("first name wrong", inviteeFirstName, acceptedInvitation.getInviteeFirstName());
    assertEquals("last name wrong", inviteeLastName, acceptedInvitation.getInviteeLastName());
    assertEquals("user name wrong", inviteeUserName, acceptedInvitation.getInviteeUserName());

    List<Invitation> it4 = invitationService.listPendingInvitationsForResource(resourceType, resourceName);
    assertTrue("invitations is not empty", it4.isEmpty());

    /**
     * Now get the invitation that we accepted
     */
    NominatedInvitation acceptedInvitation2 = (NominatedInvitation) invitationService
            .getInvitation(firstInvite.getInviteId());
    assertNotNull("get after accept does not return", acceptedInvitation2);

    /**
     * Now verify access control list
     */
    String roleName = siteService.getMembersRole(resourceName, inviteeUserName);
    assertEquals("role name wrong", roleName, inviteeRole);
    siteService.removeMembership(resourceName, inviteeUserName);

    /**
     * Check that system generated invitations can work as well
     */
    {
        Field faf = mailService.getClass().getDeclaredField("fromAddress");
        faf.setAccessible(true);
        String defaultFromAddress = (String) ReflectionUtils.getField(faf, mailService);

        AuthenticationUtil.setFullyAuthenticatedUser(USER_NOEMAIL);

        // Check invitiation
        NominatedInvitation nominatedInvitation2 = invitationService.inviteNominated(inviteeFirstName,
                inviteeLastName, USER_TWO_EMAIL, resourceType, resourceName, inviteeRole, serverPath, acceptUrl,
                rejectUrl);

        assertNotNull("nominated invitation is null", nominatedInvitation2);
        inviteId = nominatedInvitation.getInviteId();
        assertEquals("first name wrong", inviteeFirstName, nominatedInvitation2.getInviteeFirstName());
        assertEquals("last name wrong", inviteeLastName, nominatedInvitation2.getInviteeLastName());
        assertEquals("email name wrong", USER_TWO_EMAIL, nominatedInvitation2.getInviteeEmail());

        // Check the email
        MimeMessage msg = mailService.retrieveLastTestMessage();

        assertEquals(1, msg.getAllRecipients().length);
        assertEquals(USER_TWO_EMAIL, msg.getAllRecipients()[0].toString());

        assertEquals(1, msg.getFrom().length);
        assertEquals(defaultFromAddress, msg.getFrom()[0].toString());
    }
}

From source file:org.apache.nifi.processors.email.ExtractEmailAttachments.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    final ComponentLog logger = getLogger();
    final FlowFile originalFlowFile = session.get();
    if (originalFlowFile == null) {
        return;//w  w w .  j  a  va  2 s  .  c  o m
    }
    final List<FlowFile> attachmentsList = new ArrayList<>();
    final List<FlowFile> invalidFlowFilesList = new ArrayList<>();
    final List<FlowFile> originalFlowFilesList = new ArrayList<>();

    session.read(originalFlowFile, new InputStreamCallback() {
        @Override
        public void process(final InputStream rawIn) throws IOException {
            try (final InputStream in = new BufferedInputStream(rawIn)) {
                Properties props = new Properties();
                Session mailSession = Session.getDefaultInstance(props, null);
                MimeMessage originalMessage = new MimeMessage(mailSession, in);
                MimeMessageParser parser = new MimeMessageParser(originalMessage).parse();
                // RFC-2822 determines that a message must have a "From:" header
                // if a message lacks the field, it is flagged as invalid
                Address[] from = originalMessage.getFrom();
                Date sentDate = originalMessage.getSentDate();
                if (from == null || sentDate == null) {
                    // Throws MessageException due to lack of minimum required headers
                    throw new MessagingException("Message failed RFC2822 validation");
                }
                originalFlowFilesList.add(originalFlowFile);
                if (parser.hasAttachments()) {
                    final String originalFlowFileName = originalFlowFile
                            .getAttribute(CoreAttributes.FILENAME.key());
                    try {
                        for (final DataSource data : parser.getAttachmentList()) {
                            FlowFile split = session.create(originalFlowFile);
                            final Map<String, String> attributes = new HashMap<>();
                            if (StringUtils.isNotBlank(data.getName())) {
                                attributes.put(CoreAttributes.FILENAME.key(), data.getName());
                            }
                            if (StringUtils.isNotBlank(data.getContentType())) {
                                attributes.put(CoreAttributes.MIME_TYPE.key(), data.getContentType());
                            }
                            String parentUuid = originalFlowFile.getAttribute(CoreAttributes.UUID.key());
                            attributes.put(ATTACHMENT_ORIGINAL_UUID, parentUuid);
                            attributes.put(ATTACHMENT_ORIGINAL_FILENAME, originalFlowFileName);
                            split = session.append(split, new OutputStreamCallback() {
                                @Override
                                public void process(OutputStream out) throws IOException {
                                    IOUtils.copy(data.getInputStream(), out);
                                }
                            });
                            split = session.putAllAttributes(split, attributes);
                            attachmentsList.add(split);
                        }
                    } catch (FlowFileHandlingException e) {
                        // Something went wrong
                        // Removing splits that may have been created
                        session.remove(attachmentsList);
                        // Removing the original flow from its list
                        originalFlowFilesList.remove(originalFlowFile);
                        logger.error(
                                "Flowfile {} triggered error {} while processing message removing generated FlowFiles from sessions",
                                new Object[] { originalFlowFile, e });
                        invalidFlowFilesList.add(originalFlowFile);
                    }
                }
            } catch (Exception e) {
                // Another error hit...
                // Removing the original flow from its list
                originalFlowFilesList.remove(originalFlowFile);
                logger.error("Could not parse the flowfile {} as an email, treating as failure",
                        new Object[] { originalFlowFile, e });
                // Message is invalid or triggered an error during parsing
                invalidFlowFilesList.add(originalFlowFile);
            }
        }
    });

    session.transfer(attachmentsList, REL_ATTACHMENTS);

    // As per above code, originalFlowfile may be routed to invalid or
    // original depending on RFC2822 compliance.
    session.transfer(invalidFlowFilesList, REL_FAILURE);
    session.transfer(originalFlowFilesList, REL_ORIGINAL);

    if (attachmentsList.size() > 10) {
        logger.info("Split {} into {} files", new Object[] { originalFlowFile, attachmentsList.size() });
    } else if (attachmentsList.size() > 1) {
        logger.info("Split {} into {} files: {}",
                new Object[] { originalFlowFile, attachmentsList.size(), attachmentsList });
    }
}

From source file:org.apache.nifi.processors.email.ExtractEmailHeaders.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    final ComponentLog logger = getLogger();

    final List<FlowFile> invalidFlowFilesList = new ArrayList<>();
    final List<FlowFile> processedFlowFilesList = new ArrayList<>();

    final FlowFile originalFlowFile = session.get();
    if (originalFlowFile == null) {
        return;/*from ww  w . j a va  2  s. c om*/
    }

    final List<String> capturedHeadersList = Arrays
            .asList(context.getProperty(CAPTURED_HEADERS).getValue().toLowerCase().split(":"));

    final Map<String, String> attributes = new HashMap<>();
    session.read(originalFlowFile, new InputStreamCallback() {
        @Override
        public void process(final InputStream rawIn) throws IOException {
            try (final InputStream in = new BufferedInputStream(rawIn)) {
                Properties props = new Properties();
                Session mailSession = Session.getDefaultInstance(props, null);
                MimeMessage originalMessage = new MimeMessage(mailSession, in);
                MimeMessageParser parser = new MimeMessageParser(originalMessage).parse();
                // RFC-2822 determines that a message must have a "From:" header
                // if a message lacks the field, it is flagged as invalid
                Address[] from = originalMessage.getFrom();
                Date sentDate = originalMessage.getSentDate();
                if (from == null || sentDate == null) {
                    // Throws MessageException due to lack of minimum required headers
                    throw new MessagingException("Message failed RFC2822 validation");
                } else if (capturedHeadersList.size() > 0) {
                    Enumeration headers = originalMessage.getAllHeaders();
                    while (headers.hasMoreElements()) {
                        Header header = (Header) headers.nextElement();
                        if (StringUtils.isNotEmpty(header.getValue())
                                && capturedHeadersList.contains(header.getName().toLowerCase())) {
                            attributes.put("email.headers." + header.getName().toLowerCase(),
                                    header.getValue());
                        }
                    }
                }
                if (Array.getLength(originalMessage.getAllRecipients()) > 0) {
                    for (int toCount = 0; toCount < ArrayUtils
                            .getLength(originalMessage.getRecipients(Message.RecipientType.TO)); toCount++) {
                        attributes.put(EMAIL_HEADER_TO + "." + toCount,
                                originalMessage.getRecipients(Message.RecipientType.TO)[toCount].toString());
                    }
                    for (int toCount = 0; toCount < ArrayUtils
                            .getLength(originalMessage.getRecipients(Message.RecipientType.BCC)); toCount++) {
                        attributes.put(EMAIL_HEADER_BCC + "." + toCount,
                                originalMessage.getRecipients(Message.RecipientType.BCC)[toCount].toString());
                    }
                    for (int toCount = 0; toCount < ArrayUtils
                            .getLength(originalMessage.getRecipients(Message.RecipientType.CC)); toCount++) {
                        attributes.put(EMAIL_HEADER_CC + "." + toCount,
                                originalMessage.getRecipients(Message.RecipientType.CC)[toCount].toString());
                    }
                }
                // Incredibly enough RFC-2822 specified From as a "mailbox-list" so an array I returned by getFrom
                for (int toCount = 0; toCount < ArrayUtils.getLength(originalMessage.getFrom()); toCount++) {
                    attributes.put(EMAIL_HEADER_FROM + "." + toCount,
                            originalMessage.getFrom()[toCount].toString());
                }
                if (StringUtils.isNotEmpty(originalMessage.getMessageID())) {
                    attributes.put(EMAIL_HEADER_MESSAGE_ID, originalMessage.getMessageID());
                }
                if (originalMessage.getReceivedDate() != null) {
                    attributes.put(EMAIL_HEADER_RECV_DATE, originalMessage.getReceivedDate().toString());
                }
                if (originalMessage.getSentDate() != null) {
                    attributes.put(EMAIL_HEADER_SENT_DATE, originalMessage.getSentDate().toString());
                }
                if (StringUtils.isNotEmpty(originalMessage.getSubject())) {
                    attributes.put(EMAIL_HEADER_SUBJECT, originalMessage.getSubject());
                }
                // Zeroes EMAIL_ATTACHMENT_COUNT
                attributes.put(EMAIL_ATTACHMENT_COUNT, "0");
                // But insert correct value if attachments are present
                if (parser.hasAttachments()) {
                    attributes.put(EMAIL_ATTACHMENT_COUNT, String.valueOf(parser.getAttachmentList().size()));
                }

            } catch (Exception e) {
                // Message is invalid or triggered an error during parsing
                attributes.clear();
                logger.error("Could not parse the flowfile {} as an email, treating as failure",
                        new Object[] { originalFlowFile, e });
                invalidFlowFilesList.add(originalFlowFile);
            }
        }
    });

    if (attributes.size() > 0) {
        FlowFile updatedFlowFile = session.putAllAttributes(originalFlowFile, attributes);
        logger.info("Extracted {} headers into {} file", new Object[] { attributes.size(), updatedFlowFile });
        processedFlowFilesList.add(updatedFlowFile);
    }

    session.transfer(processedFlowFilesList, REL_SUCCESS);
    session.transfer(invalidFlowFilesList, REL_FAILURE);

}

From source file:org.apache.solr.handler.dataimport.FsMailEntityProcessor.java

private boolean addEnvelopToDocument(Part part, Map<String, Object> row) throws MessagingException {
    MimeMessage mail = (MimeMessage) part;
    Address[] adresses;/*from w w  w .jav  a  2  s . co m*/
    if ((adresses = mail.getFrom()) != null && adresses.length > 0) {
        String from = adresses[0].toString();
        // check if we should ignore this sender
        for (String ignore : this.ignoreFrom) {
            if (from.toLowerCase().contains(ignore)) {
                LOG.info("Ignoring email from " + from);
                return false;
            }
        }
        row.put(FROM, from);
        row.put(FROM_CLEAN, cleanAddress(from));
    } else {
        return false;
    }

    List<String> to = new ArrayList<String>();
    if ((adresses = mail.getRecipients(Message.RecipientType.TO)) != null) {
        addAddressToList(adresses, to);
    }
    if ((adresses = mail.getRecipients(Message.RecipientType.CC)) != null) {
        addAddressToList(adresses, to);
    }
    if ((adresses = mail.getRecipients(Message.RecipientType.BCC)) != null) {
        addAddressToList(adresses, to);
    }
    if (!to.isEmpty()) {
        row.put(TO_CC_BCC, to);
        List<String> cleanAddresses = cleanAddresses(to);
        row.put(TO_CC_BCC_CLEAN, cleanAddresses);
        // save first TO address into separate field
        row.put(TO, to.get(0));
        row.put(TO_CLEAN, cleanAddresses.get(0));
    }

    row.put(MESSAGE_ID, mail.getMessageID());
    row.put(SUBJECT, mail.getSubject());

    {
        Date d = mail.getSentDate();
        if (d != null) {
            row.put(SENT_DATE, d);
        }
    }
    {
        Date d = mail.getReceivedDate();
        if (d != null) {
            row.put(RECEIVED_DATE, d);
        }
    }

    List<String> flags = new ArrayList<String>();
    for (Flags.Flag flag : mail.getFlags().getSystemFlags()) {
        if (flag == Flags.Flag.ANSWERED) {
            flags.add(FLAG_ANSWERED);
        } else if (flag == Flags.Flag.DELETED) {
            flags.add(FLAG_DELETED);
        } else if (flag == Flags.Flag.DRAFT) {
            flags.add(FLAG_DRAFT);
        } else if (flag == Flags.Flag.FLAGGED) {
            flags.add(FLAG_FLAGGED);
        } else if (flag == Flags.Flag.RECENT) {
            flags.add(FLAG_RECENT);
        } else if (flag == Flags.Flag.SEEN) {
            flags.add(FLAG_SEEN);
        }
    }
    flags.addAll(Arrays.asList(mail.getFlags().getUserFlags()));
    row.put(FLAGS, flags);

    String[] hdrs = mail.getHeader("X-Mailer");
    if (hdrs != null) {
        row.put(XMAILER, hdrs[0]);
    }
    return true;
}

From source file:org.apache.solr.handler.dataimport.GmailServiceUserMailEntityProcessor.java

private boolean addEnvelopToDocument(Part part, Map<String, Object> row) throws MessagingException {
    MimeMessage mail = (MimeMessage) part;
    Address[] adresses;//w w  w .  ja v a 2s. c o  m
    if ((adresses = mail.getFrom()) != null && adresses.length > 0) {
        String from = adresses[0].toString();
        // check if we should ignore this sender
        for (String ignore : this.ignoreFrom) {
            if (from.toLowerCase().contains(ignore)) {
                LOG.info("Ignoring email from " + from);
                return false;
            }
        }
        row.put(FROM, from);
        row.put(FROM_CLEAN, cleanAddress(from));
    } else {
        return false;
    }

    List<String> to = new ArrayList<String>();
    if ((adresses = mail.getRecipients(Message.RecipientType.TO)) != null) {
        addAddressToList(adresses, to);
    }
    if ((adresses = mail.getRecipients(Message.RecipientType.CC)) != null) {
        addAddressToList(adresses, to);
    }
    if ((adresses = mail.getRecipients(Message.RecipientType.BCC)) != null) {
        addAddressToList(adresses, to);
    }
    if (!to.isEmpty()) {
        row.put(TO_CC_BCC, to);
        List<String> cleanAddresses = cleanAddresses(to);
        row.put(TO_CC_BCC_CLEAN, cleanAddresses);

        // save first TO address into separate field
        row.put(TO, to.get(0));
        row.put(TO_CLEAN, cleanAddresses.get(0));
    }

    row.put(MESSAGE_ID, mail.getMessageID());
    row.put(SUBJECT, mail.getSubject());

    {
        Date d = mail.getSentDate();
        if (d != null) {
            row.put(SENT_DATE, d);
        }
    }
    {
        Date d = mail.getReceivedDate();
        if (d != null) {
            row.put(RECEIVED_DATE, d);
        }
    }

    List<String> flags = new ArrayList<String>();
    for (Flags.Flag flag : mail.getFlags().getSystemFlags()) {
        if (flag == Flags.Flag.ANSWERED) {
            flags.add(FLAG_ANSWERED);
        } else if (flag == Flags.Flag.DELETED) {
            flags.add(FLAG_DELETED);
        } else if (flag == Flags.Flag.DRAFT) {
            flags.add(FLAG_DRAFT);
        } else if (flag == Flags.Flag.FLAGGED) {
            flags.add(FLAG_FLAGGED);
        } else if (flag == Flags.Flag.RECENT) {
            flags.add(FLAG_RECENT);
        } else if (flag == Flags.Flag.SEEN) {
            flags.add(FLAG_SEEN);
        }
    }
    flags.addAll(Arrays.asList(mail.getFlags().getUserFlags()));
    row.put(FLAGS, flags);

    String[] hdrs = mail.getHeader("X-Mailer");
    if (hdrs != null) {
        row.put(XMAILER, hdrs[0]);
    }
    return true;
}

From source file:org.elasticsearch.river.email.EmailToJson.java

public static String getSentDate(MimeMessage msg, String pattern) throws MessagingException {
    Date receivedDate = msg.getSentDate();
    if (receivedDate == null)
        return "";

    if (pattern == null || "".equals(pattern))
        pattern = "yyyy-MM-dd HH:mm:ss E";

    return new SimpleDateFormat(pattern).format(receivedDate);
}