Example usage for javax.mail Message getReceivedDate

List of usage examples for javax.mail Message getReceivedDate

Introduction

In this page you can find the example usage for javax.mail Message getReceivedDate.

Prototype

public abstract Date getReceivedDate() throws MessagingException;

Source Link

Document

Get the date this message was received.

Usage

From source file:com.sonicle.webtop.mail.Service.java

public void processGetMessage(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    MailAccount account = getAccount(request);
    String pfoldername = request.getParameter("folder");
    String puidmessage = request.getParameter("idmessage");
    String pidattach = request.getParameter("idattach");
    String providername = request.getParameter("provider");
    String providerid = request.getParameter("providerid");
    String nopec = request.getParameter("nopec");
    int idattach = 0;
    boolean isEditor = request.getParameter("editor") != null;
    boolean setSeen = ServletUtils.getBooleanParameter(request, "setseen", true);

    if (df == null) {
        df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.MEDIUM,
                environment.getProfile().getLocale());
    }//  w  w  w . j  a v  a2  s. c o m
    try {
        FolderCache mcache = null;
        Message m = null;
        IMAPMessage im = null;
        int recs = 0;
        long msguid = -1;
        String vheader[] = null;
        boolean wasseen = false;
        boolean isPECView = false;
        String sout = "{\nmessage: [\n";
        if (providername == null) {
            account.checkStoreConnected();
            mcache = account.getFolderCache(pfoldername);
            msguid = Long.parseLong(puidmessage);
            m = mcache.getMessage(msguid);
            im = (IMAPMessage) m;
            im.setPeek(us.isManualSeen());
            if (m.isExpunged())
                throw new MessagingException("Message " + puidmessage + " expunged");
            vheader = m.getHeader("Disposition-Notification-To");
            wasseen = m.isSet(Flags.Flag.SEEN);
            if (pidattach != null) {

                HTMLMailData mailData = mcache.getMailData((MimeMessage) m);
                Part part = mailData.getAttachmentPart(Integer.parseInt(pidattach));
                m = (Message) part.getContent();
                idattach = Integer.parseInt(pidattach) + 1;
            } else if (nopec == null && mcache.isPEC()) {
                String hdrs[] = m.getHeader(HDR_PEC_TRASPORTO);
                if (hdrs != null && hdrs.length > 0 && hdrs[0].equals("posta-certificata")) {
                    HTMLMailData mailData = mcache.getMailData((MimeMessage) m);
                    int parts = mailData.getAttachmentPartCount();
                    for (int i = 0; i < parts; ++i) {
                        Part p = mailData.getAttachmentPart(i);
                        if (p.isMimeType("message/rfc822")) {
                            m = (Message) p.getContent();
                            idattach = i + 1;
                            isPECView = true;
                            break;
                        }
                    }
                }
            }
        } else {
            // TODO: provider get message!!!!
            /*                WebTopService provider=wts.getServiceByName(providername);
                         MessageContentProvider mcp=provider.getMessageContentProvider(providerid);
                         m=new MimeMessage(session,mcp.getSource());
                         mcache=fcProvided;
                         mcache.addProvidedMessage(providername, providerid, m);*/
        }
        String messageid = getMessageID(m);
        String subject = m.getSubject();
        if (subject == null) {
            subject = "";
        } else {
            try {
                subject = MailUtils.decodeQString(subject);
            } catch (Exception exc) {

            }
        }
        java.util.Date d = m.getSentDate();
        if (d == null) {
            d = m.getReceivedDate();
        }
        if (d == null) {
            d = new java.util.Date(0);
        }
        String date = df.format(d).replaceAll("\\.", ":");
        String fromName = "";
        String fromEmail = "";
        Address as[] = m.getFrom();
        InternetAddress iafrom = null;
        if (as != null && as.length > 0) {
            iafrom = (InternetAddress) as[0];
            fromName = iafrom.getPersonal();
            fromEmail = adjustEmail(iafrom.getAddress());
            if (fromName == null) {
                fromName = fromEmail;
            }
        }
        sout += "{iddata:'from',value1:'" + StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(fromName))
                + "',value2:'" + StringEscapeUtils.escapeEcmaScript(fromEmail) + "',value3:0},\n";
        recs += 2;
        Address tos[] = m.getRecipients(RecipientType.TO);
        if (tos != null) {
            for (Address to : tos) {
                InternetAddress ia = (InternetAddress) to;
                String toName = ia.getPersonal();
                String toEmail = adjustEmail(ia.getAddress());
                if (toName == null) {
                    toName = toEmail;
                }
                sout += "{iddata:'to',value1:'"
                        + StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(toName)) + "',value2:'"
                        + StringEscapeUtils.escapeEcmaScript(toEmail) + "',value3:0},\n";
                ++recs;
            }
        }
        Address ccs[] = m.getRecipients(RecipientType.CC);
        if (ccs != null) {
            for (Address cc : ccs) {
                InternetAddress ia = (InternetAddress) cc;
                String ccName = ia.getPersonal();
                String ccEmail = adjustEmail(ia.getAddress());
                if (ccName == null) {
                    ccName = ccEmail;
                }
                sout += "{iddata:'cc',value1:'" + StringEscapeUtils.escapeEcmaScript(ccName) + "',value2:'"
                        + StringEscapeUtils.escapeEcmaScript(ccEmail) + "',value3:0},\n";
                ++recs;
            }
        }
        Address bccs[] = m.getRecipients(RecipientType.BCC);
        if (bccs != null)
            for (Address bcc : bccs) {
                InternetAddress ia = (InternetAddress) bcc;
                String bccName = ia.getPersonal();
                String bccEmail = adjustEmail(ia.getAddress());
                if (bccName == null) {
                    bccName = bccEmail;
                }
                sout += "{iddata:'bcc',value1:'" + StringEscapeUtils.escapeEcmaScript(bccName) + "',value2:'"
                        + StringEscapeUtils.escapeEcmaScript(bccEmail) + "',value3:0},\n";
                ++recs;
            }
        ArrayList<String> htmlparts = null;
        boolean balanceTags = isPreviewBalanceTags(iafrom);
        if (providername == null) {
            htmlparts = mcache.getHTMLParts((MimeMessage) m, msguid, false, balanceTags);
        } else {
            htmlparts = mcache.getHTMLParts((MimeMessage) m, providername, providerid, balanceTags);
        }
        HTMLMailData mailData = mcache.getMailData((MimeMessage) m);
        ICalendarRequest ir = mailData.getICalRequest();
        if (ir != null) {
            if (htmlparts.size() > 0)
                sout += "{iddata:'html',value1:'" + StringEscapeUtils.escapeEcmaScript(htmlparts.get(0))
                        + "',value2:'',value3:0},\n";
        } else {
            for (String html : htmlparts) {
                //sout += "{iddata:'html',value1:'" + OldUtils.jsEscape(html) + "',value2:'',value3:0},\n";
                sout += "{iddata:'html',value1:'" + StringEscapeUtils.escapeEcmaScript(html)
                        + "',value2:'',value3:0},\n";
                ++recs;
            }
        }

        /*if (!wasseen) {
           //if (us.isManualSeen()) {
           if (!setSeen) {
              m.setFlag(Flags.Flag.SEEN, false);
           } else {
              //if no html part, flag seen is not set
              if (htmlparts.size()==0) m.setFlag(Flags.Flag.SEEN, true);
           }
        }*/
        if (!us.isManualSeen()) {
            if (htmlparts.size() == 0)
                m.setFlag(Flags.Flag.SEEN, true);
        } else {
            if (setSeen)
                m.setFlag(Flags.Flag.SEEN, true);
        }

        int acount = mailData.getAttachmentPartCount();
        for (int i = 0; i < acount; ++i) {
            Part p = mailData.getAttachmentPart(i);
            String ctype = p.getContentType();
            Service.logger.debug("attachment " + i + " is " + ctype);
            int ix = ctype.indexOf(';');
            if (ix > 0) {
                ctype = ctype.substring(0, ix);
            }
            String cidnames[] = p.getHeader("Content-ID");
            String cidname = null;
            if (cidnames != null && cidnames.length > 0)
                cidname = mcache.normalizeCidFileName(cidnames[0]);
            boolean isInlineable = isInlineableMime(ctype);
            boolean inline = ((p.getHeader("Content-Location") != null) || (cidname != null)) && isInlineable;
            if (inline && cidname != null)
                inline = mailData.isReferencedCid(cidname);
            if (p.getDisposition() != null && p.getDisposition().equalsIgnoreCase(Part.INLINE) && inline) {
                continue;
            }

            String imgname = null;
            boolean isCalendar = ctype.equalsIgnoreCase("text/calendar")
                    || ctype.equalsIgnoreCase("text/icalendar");
            if (isCalendar) {
                imgname = "resources/" + getManifest().getId() + "/laf/" + cus.getLookAndFeel()
                        + "/ical_16.png";
            }

            String pname = getPartName(p);
            try {
                pname = MailUtils.decodeQString(pname);
            } catch (Exception exc) {
            }
            if (pname == null) {
                ix = ctype.indexOf("/");
                String fname = ctype;
                if (ix > 0) {
                    fname = ctype.substring(ix + 1);
                }
                //String ext = WT.getMediaTypeExtension(ctype);
                //if (ext == null) {
                pname = fname;
                //} else {
                //   pname = fname + "." + ext;
                //}
                if (isCalendar)
                    pname += ".ics";
            } else {
                if (isCalendar && !StringUtils.endsWithIgnoreCase(pname, ".ics"))
                    pname += ".ics";
            }
            int size = p.getSize();
            int lines = (size / 76);
            int rsize = size - (lines * 2);//(p.getSize()/4)*3;
            String iddata = ctype.equalsIgnoreCase("message/rfc822") ? "eml"
                    : (inline ? "inlineattach" : "attach");
            boolean editable = isFileEditableInDocEditor(pname);

            sout += "{iddata:'" + iddata + "',value1:'" + (i + idattach) + "',value2:'"
                    + StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(pname)) + "',value3:" + rsize
                    + ",value4:"
                    + (imgname == null ? "null" : "'" + StringEscapeUtils.escapeEcmaScript(imgname) + "'")
                    + ", editable: " + editable + " },\n";
        }
        if (!mcache.isDrafts() && !mcache.isSent() && !mcache.isSpam() && !mcache.isTrash()
                && !mcache.isArchive()) {
            if (vheader != null && vheader[0] != null && !wasseen) {
                sout += "{iddata:'receipt',value1:'" + us.getReadReceiptConfirmation() + "',value2:'"
                        + StringEscapeUtils.escapeEcmaScript(vheader[0]) + "',value3:0},\n";
            }
        }

        String h = getSingleHeaderValue(m, "Sonicle-send-scheduled");
        if (h != null && h.equals("true")) {
            java.util.Calendar scal = parseScheduleHeader(getSingleHeaderValue(m, "Sonicle-send-date"),
                    getSingleHeaderValue(m, "Sonicle-send-time"));
            if (scal != null) {
                java.util.Date sd = scal.getTime();
                String sdate = df.format(sd).replaceAll("\\.", ":");
                sout += "{iddata:'scheddate',value1:'" + StringEscapeUtils.escapeEcmaScript(sdate)
                        + "',value2:'',value3:0},\n";
            }
        }

        if (ir != null) {

            /*
            ICalendarManager calMgr = (ICalendarManager)WT.getServiceManager("com.sonicle.webtop.calendar",environment.getProfileId());
            if (calMgr != null) {
               if (ir.getMethod().equals("REPLY")) {
                  calMgr.updateEventFromICalReply(ir.getCalendar());
                  //TODO: gestire lato client una notifica di avvenuto aggiornamento
               } else {
                  Event evt = calMgr..getEvent(GetEventScope.PERSONAL_AND_INCOMING, false, ir.getUID())
                  if (evt != null) {
             UserProfileId pid = getEnv().getProfileId();
             UserProfile.Data ud = WT.getUserData(pid);
             boolean iAmOrganizer = StringUtils.equalsIgnoreCase(evt.getOrganizerAddress(), ud.getEmailAddress());
             boolean iAmOwner = pid.equals(calMgr.getCalendarOwner(evt.getCalendarId()));
                     
             if (!iAmOrganizer && !iAmOwner) {
                //TODO: gestire lato client l'aggiornamento: Accetta/Rifiuta, Aggiorna e20 dopo update/request
             }
                  }
               }
            }
            */

            ICalendarManager cm = (ICalendarManager) WT.getServiceManager("com.sonicle.webtop.calendar", true,
                    environment.getProfileId());
            if (cm != null) {
                int eid = -1;
                //Event ev=cm.getEventByScope(EventScope.PERSONAL_AND_INCOMING, ir.getUID());
                Event ev = null;
                if (ir.getMethod().equals("REPLY")) {
                    // Previous impl. forced (forceOriginal == true)
                    ev = cm.getEvent(GetEventScope.PERSONAL_AND_INCOMING, ir.getUID());
                } else {
                    ev = cm.getEvent(GetEventScope.PERSONAL_AND_INCOMING, ir.getUID());
                }

                UserProfileId pid = getEnv().getProfileId();
                UserProfile.Data ud = WT.getUserData(pid);

                if (ev != null) {
                    InternetAddress organizer = InternetAddressUtils.toInternetAddress(ev.getOrganizer());
                    boolean iAmOwner = pid.equals(cm.getCalendarOwner(ev.getCalendarId()));
                    boolean iAmOrganizer = (organizer != null)
                            && StringUtils.equalsIgnoreCase(organizer.getAddress(), ud.getEmailAddress());

                    //TODO: in reply controllo se mail combacia con quella dell'attendee che risponde...
                    //TODO: rimuovere controllo su data? dovrebbe sempre aggiornare?

                    if (iAmOwner || iAmOrganizer) {
                        eid = 0;
                        //TODO: troviamo un modo per capire se la risposta si riverisce all'ultima versione dell'evento? Nuovo campo timestamp?
                        /*
                        DateTime dtEvt = ev.getRevisionTimestamp().withMillisOfSecond(0).withZone(DateTimeZone.UTC);
                        DateTime dtICal = ICal4jUtils.fromICal4jDate(ir.getLastModified(), ICal4jUtils.getTimeZone(DateTimeZone.UTC));
                        if (dtICal.isAfter(dtEvt)) {
                           eid = 0;
                        } else {
                           eid = ev.getEventId();
                        }
                        */
                    }
                }
                sout += "{iddata:'ical',value1:'" + ir.getMethod() + "',value2:'" + ir.getUID() + "',value3:'"
                        + eid + "'},\n";
            }
        }

        sout += "{iddata:'date',value1:'" + StringEscapeUtils.escapeEcmaScript(date)
                + "',value2:'',value3:0},\n";
        sout += "{iddata:'subject',value1:'" + StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(subject))
                + "',value2:'',value3:0},\n";
        sout += "{iddata:'messageid',value1:'" + StringEscapeUtils.escapeEcmaScript(messageid)
                + "',value2:'',value3:0}\n";

        if (providername == null && !mcache.isSpecial()) {
            mcache.refreshUnreads();
        }
        long millis = System.currentTimeMillis();
        sout += "\n],\n";

        String svtags = getJSTagsArray(m.getFlags());
        if (svtags != null)
            sout += "tags: " + svtags + ",\n";

        if (isPECView) {
            sout += "pec: true,\n";
        }

        sout += "total:" + recs + ",\nmillis:" + millis + "\n}\n";
        out.println(sout);

        if (im != null)
            im.setPeek(false);

        //            if (!wasopen) folder.close(false);
    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
    }
}

From source file:org.exist.xquery.modules.mail.MessageListFunctions.java

private Sequence getMessageListAsXML(Sequence[] args, Sequence contextSequence) throws XPathException {
    Message[] msgList;//from  w  w w  .  jav  a 2 s. co m
    Sequence ret = Sequence.EMPTY_SEQUENCE;

    // was a msgList handle specified?
    if (args[0].isEmpty()) {
        throw (new XPathException(this, "Message List handle not specified"));
    }

    // get the MessageList
    long msgListHandle = ((IntegerValue) args[0].itemAt(0)).getLong();
    msgList = MailModule.retrieveMessageList(context, msgListHandle);
    if (msgList == null) {
        throw (new XPathException(this, "Invalid Message List handle specified"));
    }

    if (msgList.length > 0) {

        boolean includeHeaders = args[1].effectiveBooleanValue();

        MemTreeBuilder builder = context.getDocumentBuilder();

        builder.startDocument();
        builder.startElement(new QName("messages", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
        builder.addAttribute(new QName("count", null, null), String.valueOf(msgList.length));

        try {
            for (int i = 0; i < msgList.length; i++) {
                Message message = msgList[i];

                builder.startElement(new QName("message", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);

                builder.addAttribute(new QName("number", null, null),
                        String.valueOf(message.getMessageNumber()));

                // Sent Date
                if (message.getSentDate() != null) {
                    builder.startElement(new QName("sent", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                    builder.characters(formatDate(message.getSentDate()));
                    builder.endElement();
                }

                // Received Date
                if (message.getReceivedDate() != null) {
                    builder.startElement(new QName("received", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                            null);
                    builder.characters(formatDate(message.getReceivedDate()));
                    builder.endElement();
                }

                // From
                if (message.getFrom() != null) {
                    builder.startElement(new QName("from", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                    builder.characters(message.getFrom()[0].toString());
                    builder.endElement();
                }

                // Recipients
                builder.startElement(new QName("recipients", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                        null);
                // To Recipients
                Address[] toAddresses = message.getRecipients(Message.RecipientType.TO);
                if (toAddresses != null) {
                    for (Address to : toAddresses) {
                        builder.startElement(
                                new QName("recipient", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                        builder.addAttribute(new QName("type", null, null), "to");
                        builder.characters(to.toString());
                        builder.endElement();
                    }
                }

                // cc Recipients
                Address[] ccAddresses = message.getRecipients(Message.RecipientType.CC);
                if (ccAddresses != null) {
                    for (Address ccAddress : ccAddresses) {
                        builder.startElement(
                                new QName("recipient", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                        builder.addAttribute(new QName("type", null, null), "cc");
                        builder.characters(ccAddress.toString());
                        builder.endElement();
                    }
                }

                // bcc Recipients
                Address[] bccAddresses = message.getRecipients(Message.RecipientType.BCC);
                if (bccAddresses != null) {
                    for (Address bccAddress : bccAddresses) {
                        builder.startElement(
                                new QName("recipient", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                        builder.addAttribute(new QName("type", null, null), "bcc");
                        builder.characters(bccAddress.toString());
                        builder.endElement();
                    }
                }
                builder.endElement();

                // Flags

                Flags flags = message.getFlags();
                Flags.Flag[] systemFlags = flags.getSystemFlags();
                String[] userFlags = flags.getUserFlags();

                if (systemFlags.length > 0 || userFlags.length > 0) {
                    builder.startElement(new QName("flags", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);

                    for (Flags.Flag systemFlag : systemFlags) {
                        if (systemFlag == Flags.Flag.ANSWERED) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "answered");
                            builder.endElement();
                        } else if (systemFlag == Flags.Flag.DELETED) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "deleted");
                            builder.endElement();
                        } else if (systemFlag == Flags.Flag.DRAFT) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "draft");
                            builder.endElement();
                        } else if (systemFlag == Flags.Flag.FLAGGED) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "flagged");
                            builder.endElement();
                        } else if (systemFlag == Flags.Flag.RECENT) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "recent");
                            builder.endElement();
                        } else if (systemFlag == Flags.Flag.SEEN) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "seen");
                            builder.endElement();
                        }
                    }

                    for (String userFlag : userFlags) {
                        builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                null);
                        builder.addAttribute(new QName("type", null, null), "user");
                        builder.addAttribute(new QName("value", null, null), userFlag);
                        builder.endElement();
                    }

                    builder.endElement();
                }

                // Headers

                if (includeHeaders) {
                    Enumeration headers = message.getAllHeaders();

                    if (headers.hasMoreElements()) {
                        builder.startElement(new QName("headers", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                null);

                        while (headers.hasMoreElements()) {
                            Header header = (Header) headers.nextElement();

                            builder.startElement(
                                    new QName("header", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                            builder.addAttribute(new QName("name", null, null), header.getName());
                            builder.addAttribute(new QName("value", null, null), header.getValue());
                            builder.endElement();
                        }

                        builder.endElement();
                    }
                }

                // Subject
                builder.startElement(new QName("subject", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                builder.characters(message.getSubject());
                builder.endElement();

                builder.endElement();
            }
        } catch (MessagingException me) {
            throw (new XPathException(this, "Failed to retrieve messages from list", me));
        }

        builder.endElement();

        ret = (NodeValue) builder.getDocument().getDocumentElement();
    }

    return (ret);
}

From source file:org.nuxeo.cm.mail.actionpipe.ExtractMessageInformation.java

@Override
@SuppressWarnings("deprecation")
public boolean execute(ExecutionContext context) throws MessagingException {
    File tmpOutput = null;/*from  w  ww .  j a v a2  s . c o m*/
    OutputStream out = null;
    try {
        Message originalMessage = context.getMessage();
        if (log.isDebugEnabled()) {
            log.debug("Transforming message, original subject: " + originalMessage.getSubject());
        }

        // fully load the message before trying to parse to
        // override most of server bugs, see
        // http://java.sun.com/products/javamail/FAQ.html#imapserverbug
        Message message;
        if (originalMessage instanceof MimeMessage) {
            message = new MimeMessage((MimeMessage) originalMessage);
            if (log.isDebugEnabled()) {
                log.debug("Transforming message after full load: " + message.getSubject());
            }
        } else {
            // stuck with the original one
            message = originalMessage;
        }

        Address[] from = message.getFrom();
        if (from != null) {
            Address addr = from[0];
            if (addr instanceof InternetAddress) {
                InternetAddress iAddr = (InternetAddress) addr;
                context.put(SENDER_KEY, iAddr.getPersonal());
                context.put(SENDER_EMAIL_KEY, iAddr.getAddress());
            } else {
                context.put(SENDER_KEY, addr.toString());
            }
        }
        Date receivedDate = message.getReceivedDate();
        if (receivedDate == null) {
            // try to get header manually
            String[] dateHeader = message.getHeader("Date");
            if (dateHeader != null) {
                try {
                    long time = Date.parse(dateHeader[0]);
                    receivedDate = new Date(time);
                } catch (IllegalArgumentException e) {
                    // nevermind
                }
            }
        }

        if (receivedDate != null) {
            Calendar date = Calendar.getInstance();
            date.setTime(receivedDate);
            context.put(RECEPTION_DATE_KEY, date);
        }
        String subject = message.getSubject();
        if (subject != null) {
            subject = subject.trim();
        }
        if (subject == null || "".equals(subject)) {
            subject = "<Unknown>";
        }
        context.put(SUBJECT_KEY, subject);
        String[] messageIdHeader = message.getHeader("Message-ID");
        if (messageIdHeader != null) {
            context.put(MESSAGE_ID_KEY, messageIdHeader[0]);
        }

        // TODO: pass it through initial context
        MimetypeRegistry mimeService = (MimetypeRegistry) context.getInitialContext().get(MIMETYPE_SERVICE_KEY);
        if (mimeService == null) {
            log.error("Could not retrieve mimetype service");
        }

        // add all content as first blob
        tmpOutput = File.createTempFile("injectedEmail", ".eml");
        Framework.trackFile(tmpOutput, tmpOutput);
        out = new FileOutputStream(tmpOutput);
        message.writeTo(out);
        Blob blob = Blobs.createBlob(tmpOutput, MESSAGE_RFC822_MIMETYPE, null, subject + ".eml");

        List<Blob> blobs = new ArrayList<>();
        blobs.add(blob);
        context.put(ATTACHMENTS_KEY, blobs);

        // process content
        getAttachmentParts(message, subject, mimeService, context);
        return true;
    } catch (IOException e) {
        log.error(e);
    } finally {
        IOUtils.closeQuietly(out);
    }
    return false;
}

From source file:org.nuxeo.ecm.platform.mail.action.TransformMessageAction.java

public boolean execute(ExecutionContext context) throws MessagingException {
    Message message = context.getMessage();
    if (log.isDebugEnabled()) {
        log.debug("Transforming message" + message.getSubject());
    }/*from   w  w  w .  ja  v a 2  s . c  o  m*/
    if (message.getFrom() != null && message.getFrom().length != 0) {
        List<String> contributors = new ArrayList<String>();
        for (Address ad : message.getFrom()) {
            contributors.add(safelyDecodeText(ad.toString()));
        }
        dcSchema.put("contributors", contributors);
        dcSchema.put("creator", contributors.get(0));
        dcSchema.put("created", message.getReceivedDate());
    }
    if (message.getAllRecipients() != null && message.getAllRecipients().length != 0) {
        List<String> recipients = new ArrayList<String>();
        for (Address address : message.getAllRecipients()) {
            recipients.add(safelyDecodeText(address.toString()));
        }
        mailSchema.put("recipients", recipients);
    }
    if (message instanceof MimeMessage) {
        try {
            processMimeMessage((MimeMessage) message);
        } catch (IOException e) {
            throw new MessagingException(e.getMessage(), e);
        }
    }
    mailSchema.put("text", text.toString());
    dcSchema.put("title", message.getSubject());
    context.put("transformed", schemas);
    return true;
}

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

/**
 * Retrieve mail for user./*from w ww . jav  a2 s  .com*/
 *
 * @param userType = "P" if logged in user is a provider
 *                   "T" if logged in user is a patient
 * @param userId = unique id of logged in user.
 * @param login = email server user name of logged in user.
 * @param pswd  = password of logged in user.
 * @param folderName = 
 * @param displayName = full name
 * @param onlyNew =
 *
 * @return
 * @throws java.lang.Exception
 */
//private  //DBG ONLY - REMOVE COMMENT MARKS
public List<SummaryData> retrieveMail(String userType, String userId, String patientId, String login,
        String pswd, String folderName, String patientName, boolean onlyNew, String mailHost, String mailUrl)
        throws Exception, DatatypeConfigurationException {
    List<SummaryData> dataList = new LinkedList<SummaryData>();
    IMAPSSLStore sslStore = null;
    IMAPFolder currentFolder = null;
    String folderToOpen = folderName;

    System.out.println("===> retrieveMail Incoming params:");
    System.out.println("===>     mailHost=" + mailHost);
    System.out.println("===>      mailUrl=" + mailUrl);
    System.out.println("===>    maillogin=" + login);
    System.out.println("===>   folderName=" + folderName);
    try {
        //Get session
        Session session = Session.getInstance(new Properties());
        URLName urlName = new URLName(mailUrl);
        //Get the sslStore
        sslStore = new IMAPSSLStore(session, urlName);
        sslStore.connect(mailHost, login, pswd);

        folderToOpen = this.mapKmrLocationToImapFolder(folderName, this.host);

        currentFolder = (IMAPFolder) sslStore.getFolder(folderToOpen);
        currentFolder.open(Folder.READ_ONLY);

        Message[] allMessages = currentFolder.getMessages();

        GregorianCalendar cal = new GregorianCalendar();

        System.out.println("====> FILTER PARAMS for Emails:");
        System.out.println("====>     folder = " + folderToOpen);
        System.out.println("====>     User   = " + login);
        //            System.out.println("====>     from   = "+ patientName +"/"+ patientEmail);
        //            System.out.println("====>     ptid   = "+ patientId);
        System.out.println("====> Total Emails found = " + allMessages.length);
        System.out.println();

        // TMN - CHECK SLOW PERFORMANCE ISSUE HERE:

        //Loop through each email and find ONLY the ones required for return.
        for (Message msg : allMessages) {
            if (msg == null) {
                continue;
            }

            // Keep this in case we want to search entire message
            //
            //                OutputStream os = new ByteArrayOutputStream();
            //                msg.writeTo(os);
            //                String msgContent = os.toString();

            SummaryData summaryData = new SummaryData();
            summaryData.setDataSource(DATA_SOURCE);

            String from = "";
            Address[] fromAddr = msg.getFrom();

            if (fromAddr != null && fromAddr.length > 0) {

                String fromFull = fromAddr[0].toString();
                from = getContactIdFromEmail(extractEmailAddressFromSender(fromFull));

                //System.out.println("retrieveMail: FROM=" + fromFull + " ldap.cn=" + from);

            }

            //------------------------------------------------------
            //FILTERING: Check to exclude email if
            //     0) patientId is passed in as a param
            // AND 1) email does NOT contain PATIENTID=<patientId>
            // AND 2) email FROM field <> patientName
            // AND 3) email FROM field <> patientEmail.
            //
            // because must becoming from EMR inbox and looking for emails
            // addressed to userId BUT only ABOUT or FROM patientId.
            //------------------------------------------------------

            summaryData.setFrom(from);
            summaryData.setAuthor(summaryData.getFrom());
            cal.setTime(msg.getReceivedDate());
            summaryData.setDateCreated(DatatypeFactory.newInstance().newXMLGregorianCalendar(cal));

            summaryData.setDescription(msg.getSubject());

            summaryData.setItemId(userType + userId + ITEM_ID_SEPARATER + msg.getFolder().getName()
                    + ITEM_ID_SEPARATER + msg.getHeader("Message-ID")[0]);

            //this.printMsgIdSubject(msg); //DBG printout

            boolean msgRead = msg.isSet(Flags.Flag.SEEN);
            addNameValue(summaryData.getItemValues(), ITEM_READ, String.valueOf(msgRead));

            boolean msgStar = msg.isSet(Flags.Flag.FLAGGED);
            if (msgStar) {
                addNameValue(summaryData.getItemValues(), ITEM_STARRED, "Starred");
            }

            addNameValue(summaryData.getItemValues(), ITEM_REPLIED,
                    String.valueOf(msg.isSet(Flags.Flag.ANSWERED)));
            addNameValue(summaryData.getItemValues(), "MESSAGE_TYPE", msg.getFolder().getName());
            if (onlyNew) {
                if (!msg.isSet(Flags.Flag.SEEN)) {
                    dataList.add(summaryData);
                }
            } else {
                dataList.add(summaryData);
            }
        }

    } catch (MessagingException me) {
        log.error("Error in processing email");
        me.printStackTrace();
    } finally {
        // Close connections

        if (currentFolder != null) {
            try {
                currentFolder.close(false);
            } catch (Exception e) {
            }
        }

        if (sslStore != null) {
            try {
                sslStore.close();
            } catch (Exception e) {
            }
        }
    }

    return dataList;
}