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:de.saly.elasticsearch.support.IndexableMailMessage.java

public static IndexableMailMessage fromJavaMailMessage(final Message jmm, final boolean withTextContent,
        final boolean withAttachments, final boolean stripTags, List<String> headersToFields)
        throws MessagingException, IOException {
    final IndexableMailMessage im = new IndexableMailMessage();

    @SuppressWarnings("unchecked")
    final Enumeration<Header> allHeaders = jmm.getAllHeaders();

    final Set<IndexableHeader> headerList = new HashSet<IndexableHeader>();
    while (allHeaders.hasMoreElements()) {
        final Header h = allHeaders.nextElement();
        headerList.add(new IndexableHeader(h.getName(), h.getValue()));
    }/*from  w ww .  j ava  2 s  .  c  o m*/

    im.setHeaders(headerList.toArray(new IndexableHeader[headerList.size()]));

    im.setSelectedHeaders(extractHeaders(im.getHeaders(), headersToFields));

    if (jmm.getFolder() instanceof POP3Folder) {
        im.setPopId(((POP3Folder) jmm.getFolder()).getUID(jmm));
        im.setMailboxType("POP");

    } else {
        im.setMailboxType("IMAP");
    }

    if (jmm.getFolder() instanceof UIDFolder) {
        im.setUid(((UIDFolder) jmm.getFolder()).getUID(jmm));
    }

    im.setFolderFullName(jmm.getFolder().getFullName());

    im.setFolderUri(jmm.getFolder().getURLName().toString());

    im.setContentType(jmm.getContentType());
    im.setSubject(jmm.getSubject());
    im.setSize(jmm.getSize());
    im.setSentDate(jmm.getSentDate());

    if (jmm.getReceivedDate() != null) {
        im.setReceivedDate(jmm.getReceivedDate());
    }

    if (jmm.getFrom() != null && jmm.getFrom().length > 0) {
        im.setFrom(Address.fromJavaMailAddress(jmm.getFrom()[0]));
    }

    if (jmm.getRecipients(RecipientType.TO) != null) {
        im.setTo(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.TO)));
    }

    if (jmm.getRecipients(RecipientType.CC) != null) {
        im.setCc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.CC)));
    }

    if (jmm.getRecipients(RecipientType.BCC) != null) {
        im.setBcc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.BCC)));
    }

    if (withTextContent) {

        // try {

        String textContent = getText(jmm, 0);

        if (stripTags) {
            textContent = stripTags(textContent);
        }

        im.setTextContent(textContent);
        // } catch (final Exception e) {
        // logger.error("Unable to retrieve text content for message {} due to {}",
        // e, ((MimeMessage) jmm).getMessageID(), e);
        // }
    }

    if (withAttachments) {

        try {
            final Object content = jmm.getContent();

            // look for attachments
            if (jmm.isMimeType("multipart/*") && content instanceof Multipart) {
                List<ESAttachment> attachments = new ArrayList<ESAttachment>();

                final Multipart multipart = (Multipart) content;

                for (int i = 0; i < multipart.getCount(); i++) {
                    final BodyPart bodyPart = multipart.getBodyPart(i);
                    if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())
                            && !StringUtils.isNotBlank(bodyPart.getFileName())) {
                        continue; // dealing with attachments only
                    }
                    final InputStream is = bodyPart.getInputStream();
                    final byte[] bytes = IOUtils.toByteArray(is);
                    IOUtils.closeQuietly(is);
                    attachments.add(new ESAttachment(bodyPart.getContentType(), bytes, bodyPart.getFileName()));
                }

                if (!attachments.isEmpty()) {
                    im.setAttachments(attachments.toArray(new ESAttachment[attachments.size()]));
                    im.setAttachmentCount(im.getAttachments().length);
                    attachments.clear();
                    attachments = null;
                }

            }
        } catch (final Exception e) {
            logger.error(
                    "Error indexing attachments (message will be indexed but without attachments) due to {}", e,
                    e.toString());
        }

    }

    im.setFlags(IMAPUtils.toStringArray(jmm.getFlags()));
    im.setFlaghashcode(jmm.getFlags().hashCode());

    return im;
}

From source file:de.saly.elasticsearch.importer.imap.support.IndexableMailMessage.java

public static IndexableMailMessage fromJavaMailMessage(final Message jmm, final boolean withTextContent,
        final boolean withHtmlContent, final boolean preferHtmlContent, final boolean withAttachments,
        final boolean stripTags, List<String> headersToFields) throws MessagingException, IOException {
    final IndexableMailMessage im = new IndexableMailMessage();

    @SuppressWarnings("unchecked")
    final Enumeration<Header> allHeaders = jmm.getAllHeaders();

    final Set<IndexableHeader> headerList = new HashSet<IndexableHeader>();
    while (allHeaders.hasMoreElements()) {
        final Header h = allHeaders.nextElement();
        headerList.add(new IndexableHeader(h.getName(), h.getValue()));
    }//from   ww w.  j  a  va2s. c o  m

    im.setHeaders(headerList.toArray(new IndexableHeader[headerList.size()]));

    im.setSelectedHeaders(extractHeaders(im.getHeaders(), headersToFields));

    if (jmm.getFolder() instanceof POP3Folder) {
        im.setPopId(((POP3Folder) jmm.getFolder()).getUID(jmm));
        im.setMailboxType("POP");

    } else {
        im.setMailboxType("IMAP");
    }

    if (jmm.getFolder() instanceof UIDFolder) {
        im.setUid(((UIDFolder) jmm.getFolder()).getUID(jmm));
    }

    im.setFolderFullName(jmm.getFolder().getFullName());

    im.setFolderUri(jmm.getFolder().getURLName().toString());

    im.setContentType(jmm.getContentType());
    im.setSubject(jmm.getSubject());
    im.setSize(jmm.getSize());
    im.setSentDate(jmm.getSentDate());

    if (jmm.getReceivedDate() != null) {
        im.setReceivedDate(jmm.getReceivedDate());
    }

    if (jmm.getFrom() != null && jmm.getFrom().length > 0) {
        im.setFrom(Address.fromJavaMailAddress(jmm.getFrom()[0]));
    }

    if (jmm.getRecipients(RecipientType.TO) != null) {
        im.setTo(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.TO)));
    }

    if (jmm.getRecipients(RecipientType.CC) != null) {
        im.setCc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.CC)));
    }

    if (jmm.getRecipients(RecipientType.BCC) != null) {
        im.setBcc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.BCC)));
    }

    if (withTextContent) {

        // try {

        String textContent = getText(jmm, 0, preferHtmlContent);

        if (stripTags) {
            textContent = stripTags(textContent);
        }

        im.setTextContent(textContent);
        // } catch (final Exception e) {
        // logger.error("Unable to retrieve text content for message {} due to {}",
        // e, ((MimeMessage) jmm).getMessageID(), e);
        // }
    }

    if (withHtmlContent) {

        // try {

        String htmlContent = getText(jmm, 0, true);

        im.setHtmlContent(htmlContent);
        // } catch (final Exception e) {
        // logger.error("Unable to retrieve text content for message {} due to {}",
        // e, ((MimeMessage) jmm).getMessageID(), e);
        // }
    }

    if (withAttachments) {

        try {
            final Object content = jmm.getContent();

            // look for attachments
            if (jmm.isMimeType("multipart/*") && content instanceof Multipart) {
                List<ESAttachment> attachments = new ArrayList<ESAttachment>();

                final Multipart multipart = (Multipart) content;

                for (int i = 0; i < multipart.getCount(); i++) {
                    final BodyPart bodyPart = multipart.getBodyPart(i);
                    if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())
                            && !StringUtils.isNotBlank(bodyPart.getFileName())) {
                        continue; // dealing with attachments only
                    }
                    final InputStream is = bodyPart.getInputStream();
                    final byte[] bytes = IOUtils.toByteArray(is);
                    IOUtils.closeQuietly(is);
                    attachments.add(new ESAttachment(bodyPart.getContentType(), bytes, bodyPart.getFileName()));
                }

                if (!attachments.isEmpty()) {
                    im.setAttachments(attachments.toArray(new ESAttachment[attachments.size()]));
                    im.setAttachmentCount(im.getAttachments().length);
                    attachments.clear();
                    attachments = null;
                }

            }
        } catch (final Exception e) {
            logger.error(
                    "Error indexing attachments (message will be indexed but without attachments) due to {}", e,
                    e.toString());
        }

    }

    im.setFlags(IMAPUtils.toStringArray(jmm.getFlags()));
    im.setFlaghashcode(jmm.getFlags().hashCode());

    return im;
}

From source file:com.naryx.tagfusion.cfm.mail.cfMailMessageData.java

private boolean extractMessage(Message Mess, long messageID, String attachURI, String attachDIR) {
    cfArrayData ADD = cfArrayData.createArray(1);

    try {/*from  w  w  w.j  a va  2s. co  m*/

        setData("subject", new cfStringData(Mess.getSubject()));
        setData("id", new cfNumberData(messageID));

        //--- Pull out all the headers
        cfStructData headers = new cfStructData();
        Enumeration<Header> eH = Mess.getAllHeaders();
        String headerKey;
        while (eH.hasMoreElements()) {
            Header hdr = eH.nextElement();

            headerKey = hdr.getName().replace('-', '_').toLowerCase();
            if (headers.containsKey(headerKey)) {
                headers.setData(headerKey,
                        new cfStringData(headers.getData(headerKey).toString() + ";" + hdr.getValue()));
            } else
                headers.setData(headerKey, new cfStringData(hdr.getValue()));
        }

        setData("headers", headers);

        // Get the Date
        Date DD = Mess.getReceivedDate();
        if (DD == null)
            setData("rxddate", new cfDateData(System.currentTimeMillis()));
        else
            setData("rxddate", new cfDateData(DD.getTime()));

        DD = Mess.getSentDate();
        if (DD == null)
            setData("sentdate", new cfDateData(System.currentTimeMillis()));
        else
            setData("sentdate", new cfDateData(DD.getTime()));

        // Get the FROM field
        Address[] from = Mess.getFrom();
        if (from != null && from.length > 0) {
            cfStructData sdFrom = new cfStructData();
            String name = ((InternetAddress) from[0]).getPersonal();
            if (name != null)
                sdFrom.setData("name", new cfStringData(name));

            sdFrom.setData("email", new cfStringData(((InternetAddress) from[0]).getAddress()));
            setData("from", sdFrom);
        }

        //--[ Get the TO/CC/BCC field
        cfArrayData AD = extractAddresses(Mess.getRecipients(Message.RecipientType.TO));
        if (AD != null)
            setData("to", AD);

        AD = extractAddresses(Mess.getRecipients(Message.RecipientType.CC));
        if (AD != null)
            setData("cc", AD);

        AD = extractAddresses(Mess.getRecipients(Message.RecipientType.BCC));
        if (AD != null)
            setData("bcc", AD);

        AD = extractAddresses(Mess.getReplyTo());
        if (AD != null)
            setData("replyto", AD);

        //--[ Set the flags
        setData("answered", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.ANSWERED)));
        setData("deleted", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.DELETED)));
        setData("draft", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.DRAFT)));
        setData("flagged", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.FLAGGED)));
        setData("recent", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.RECENT)));
        setData("seen", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.SEEN)));

        setData("size", new cfNumberData(Mess.getSize()));
        setData("lines", new cfNumberData(Mess.getLineCount()));

        String tmp = Mess.getContentType();
        if (tmp.indexOf(";") != -1)
            tmp = tmp.substring(0, tmp.indexOf(";"));

        setData("mimetype", new cfStringData(tmp));

        // Get the body of the email
        extractBody(Mess, ADD, attachURI, attachDIR);

    } catch (Exception E) {
        return false;
    }

    setData("body", ADD);
    return true;
}

From source file:com.email.ReceiveEmail.java

/**
 * Saved the list of all of the TO, FROM, CC, BCC, and dates
 *
 * @param m Message/*from w ww  .  j a v a 2 s  .c o  m*/
 * @param p Part
 * @param eml EmailMessageModel
 * @return EmailMessageModel
 */
private static EmailMessageModel saveEnvelope(Message m, Part p, EmailMessageModel eml) {
    String to = "";
    String cc = "";
    String bcc = "";

    try {
        Address[] address;

        //From
        if ((address = m.getFrom()) != null) {
            for (Address addy : address) {
                eml.setEmailFrom(addy.toString());
            }
        }

        //to
        if ((address = m.getRecipients(Message.RecipientType.TO)) != null) {
            for (int j = 0; j < address.length; j++) {
                if (j == 0) {
                    to = address[j].toString();
                } else {
                    to += "; " + address[j].toString();
                }
            }
        }
        eml.setEmailTo(removeEmojiAndSymbolFromString(to));

        //CC
        if ((address = m.getRecipients(Message.RecipientType.CC)) != null) {

            for (int j = 0; j < address.length; j++) {
                if (j == 0) {
                    cc = address[j].toString();
                } else {
                    cc += "; " + address[j].toString();
                }
            }
        }
        eml.setEmailCC(removeEmojiAndSymbolFromString(cc));

        //BCC
        if ((address = m.getRecipients(Message.RecipientType.BCC)) != null) {
            for (int j = 0; j < address.length; j++) {
                if (j == 0) {
                    bcc = address[j].toString();
                } else {
                    bcc += "; " + address[j].toString();
                }
            }
        }
        eml.setEmailBCC(removeEmojiAndSymbolFromString(bcc));

        //subject
        if (m.getSubject() == null) {
            eml.setEmailSubject("");
        } else {
            eml.setEmailSubject(removeEmojiAndSymbolFromString(m.getSubject().replace("'", "\"")));
        }

        //date
        eml.setSentDate(new java.sql.Timestamp(m.getSentDate().getTime()));
        eml.setReceivedDate(new java.sql.Timestamp(m.getReceivedDate().getTime()));

        //Get email body
        String emailBody = getEmailBodyText(p);

        // clean email Body
        emailBody = StringUtilities.replaceOfficeTags(emailBody);

        if (StringUtilities.isHtml(emailBody)) {
            Source htmlSource = new Source(emailBody);
            Segment htmlSeg = new Segment(htmlSource, 0, htmlSource.length());
            Renderer htmlRend = new Renderer(htmlSeg);
            emailBody = htmlRend.toString();
        }

        eml.setEmailBody(removeEmojiAndSymbolFromString(emailBody));

    } catch (MessagingException ex) {
        ExceptionHandler.Handle(ex);
    }
    return eml;
}

From source file:ch.entwine.weblounge.bridge.mail.MailAggregator.java

/**
 * Aggregates the e-mail message by reading it and turning it either into a
 * page or a file upload./*from   w  w w  . j av  a  2s.c  om*/
 * 
 * @param message
 *          the e-mail message
 * @param site
 *          the site to publish to
 * @throws MessagingException
 *           if fetching the message data fails
 * @throws IOException
 *           if writing the contents to the output stream fails
 */
protected Page aggregate(Message message, Site site)
        throws IOException, MessagingException, IllegalArgumentException {

    ResourceURI uri = new PageURIImpl(site, UUID.randomUUID().toString());
    Page page = new PageImpl(uri);
    Language language = site.getDefaultLanguage();

    // Extract title and subject. Without these two, creating a page is not
    // feasible, therefore both messages throw an IllegalArgumentException if
    // the fields are not present.
    String title = getSubject(message);
    String author = getAuthor(message);

    // Collect default settings
    PageTemplate template = site.getDefaultTemplate();
    if (template == null)
        throw new IllegalStateException("Missing default template in site '" + site + "'");
    String stage = template.getStage();
    if (StringUtils.isBlank(stage))
        throw new IllegalStateException(
                "Missing stage definition in template '" + template.getIdentifier() + "'");

    // Standard fields
    page.setTitle(title, language);
    page.setTemplate(template.getIdentifier());
    page.setPublished(new UserImpl(site.getAdministrator()), message.getReceivedDate(), null);

    // TODO: Translate e-mail "from" into site user and throw if no such
    // user can be found
    page.setCreated(site.getAdministrator(), message.getSentDate());

    // Start looking at the message body
    String contentType = message.getContentType();
    if (StringUtils.isBlank(contentType))
        throw new IllegalArgumentException("Message content type is unspecified");

    // Text body
    if (contentType.startsWith("text/plain")) {
        // TODO: Evaluate charset
        String body = null;
        if (message.getContent() instanceof String)
            body = (String) message.getContent();
        else if (message.getContent() instanceof InputStream)
            body = IOUtils.toString((InputStream) message.getContent());
        else
            throw new IllegalArgumentException("Message body is of unknown type");
        return handleTextPlain(body, page, language);
    }

    // HTML body
    if (contentType.startsWith("text/html")) {
        // TODO: Evaluate charset
        return handleTextHtml((String) message.getContent(), page, null);
    }

    // Multipart body
    else if ("mime/multipart".equalsIgnoreCase(contentType)) {
        Multipart mp = (Multipart) message.getContent();
        for (int i = 0, n = mp.getCount(); i < n; i++) {
            Part part = mp.getBodyPart(i);
            String disposition = part.getDisposition();
            if (disposition == null) {
                MimeBodyPart mbp = (MimeBodyPart) part;
                if (mbp.isMimeType("text/plain")) {
                    return handleTextPlain((String) mbp.getContent(), page, null);
                } else {
                    // TODO: Implement special non-attachment cases here of
                    // image/gif, text/html, ...
                    throw new UnsupportedOperationException("Multipart message bodies of type '"
                            + mbp.getContentType() + "' are not yet supported");
                }
            } else if (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE)) {
                logger.info("Skipping message attachment " + part.getFileName());
                // saveFile(part.getFileName(), part.getInputStream());
            }
        }

        throw new IllegalArgumentException("Multipart message did not contain any recognizable content");
    }

    // ?
    else {
        throw new IllegalArgumentException("Message body is of unknown type '" + contentType + "'");
    }
}

From source file:com.jaeksoft.searchlib.crawler.mailbox.crawler.MailboxAbstractCrawler.java

final public void readMessage(IndexDocument crawlIndexDocument, IndexDocument parserIndexDocument,
        Folder folder, Message message, String id) throws Exception {

    crawlIndexDocument.addString(MailboxFieldEnum.message_id.name(), id);
    crawlIndexDocument.addString(MailboxFieldEnum.message_number.name(),
            Integer.toString(message.getMessageNumber()));
    if (message instanceof MimeMessage)
        crawlIndexDocument.addString(MailboxFieldEnum.content_id.name(),
                ((MimeMessage) message).getContentID());
    crawlIndexDocument.addString(MailboxFieldEnum.subject.name(), message.getSubject());
    putAddresses(crawlIndexDocument, message.getFrom(), MailboxFieldEnum.from_address.name(),
            MailboxFieldEnum.from_personal.name());
    putAddresses(crawlIndexDocument, message.getReplyTo(), MailboxFieldEnum.reply_to_address.name(),
            MailboxFieldEnum.reply_to_personal.name());
    putAddresses(crawlIndexDocument, message.getRecipients(RecipientType.TO),
            MailboxFieldEnum.recipient_to_address.name(), MailboxFieldEnum.recipient_to_personal.name());
    putAddresses(crawlIndexDocument, message.getRecipients(RecipientType.CC),
            MailboxFieldEnum.recipient_cc_address.name(), MailboxFieldEnum.recipient_cc_personal.name());
    putAddresses(crawlIndexDocument, message.getRecipients(RecipientType.BCC),
            MailboxFieldEnum.recipient_bcc_address.name(), MailboxFieldEnum.recipient_bcc_personal.name());
    Date dt = message.getSentDate();
    if (dt != null)
        crawlIndexDocument.addString(MailboxFieldEnum.send_date.name(), dt.toString());
    dt = message.getReceivedDate();
    if (dt != null)
        crawlIndexDocument.addString(MailboxFieldEnum.received_date.name(), dt.toString());
    if (message.isSet(Flag.ANSWERED))
        crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "ANSWERED");
    if (message.isSet(Flag.DELETED))
        crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "DELETED");
    if (message.isSet(Flag.DRAFT))
        crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "DRAFT");
    if (message.isSet(Flag.FLAGGED))
        crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "FLAGGED");
    if (message.isSet(Flag.SEEN))
        crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "SEEN");

    if (message instanceof MimeMessage) {
        MimeMessageParser mimeMessageParser = new MimeMessageParser((MimeMessage) message).parse();

        crawlIndexDocument.addString(MailboxFieldEnum.html_content.name(), mimeMessageParser.getHtmlContent());
        crawlIndexDocument.addString(MailboxFieldEnum.plain_content.name(),
                mimeMessageParser.getPlainContent());
        for (DataSource dataSource : mimeMessageParser.getAttachmentList()) {
            crawlIndexDocument.addString(MailboxFieldEnum.email_attachment_name.name(), dataSource.getName());
            crawlIndexDocument.addString(MailboxFieldEnum.email_attachment_type.name(),
                    dataSource.getContentType());
            if (parserSelector == null)
                continue;
            Parser attachParser = parserSelector.parseStream(null, dataSource.getName(),
                    dataSource.getContentType(), null, dataSource.getInputStream(), null, null, null);
            if (attachParser == null)
                continue;
            List<ParserResultItem> parserResults = attachParser.getParserResults();
            if (parserResults != null)
                for (ParserResultItem parserResult : parserResults)
                    crawlIndexDocument.addFieldIndexDocument(MailboxFieldEnum.email_attachment_content.name(),
                            parserResult.getParserDocument());
        }// w ww  . ja  v  a  2s  . c  o  m
    }
}

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

private void outputJarMailFolder(String foldername, Message msgs[], JarOutputStream jos) throws Exception {
    int digits = (msgs.length > 0 ? (int) Math.log10(msgs.length) + 1 : 1);
    for (int i = 0; i < msgs.length; ++i) {
        Message msg = msgs[i];
        String subject = msg.getSubject();
        if (subject != null)
            subject = subject.replace('/', '_').replace('\\', '_').replace(':', '-');
        else/*  w w  w.j  a v  a  2s.  c om*/
            subject = "";
        java.util.Date date = msg.getReceivedDate();
        if (date == null)
            date = new java.util.Date();

        String fname = LangUtils.zerofill(i + 1, digits) + " - " + subject + ".eml";
        String fullname = null;
        if (foldername != null && !foldername.isEmpty())
            fullname = foldername + "/" + fname;
        else
            fullname = fname;
        JarEntry je = new JarEntry(fullname);
        je.setTime(date.getTime());
        jos.putNextEntry(je);
        msg.writeTo(jos);
        jos.closeEntry();
    }
    jos.flush();
}

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

public void dmsArchiveMessages(FolderCache from, long nuids[], String idcategory, String idsubcategory,
        boolean fullthreads) throws MessagingException, FileNotFoundException, IOException {
    UserProfile profile = environment.getProfile();
    String archiveto = ss.getDmsArchivePath();
    for (long nuid : nuids) {
        Message msg = from.getMessage(nuid);

        String id = getMessageID(msg);
        if (id.startsWith("<")) {
            id = id.substring(1, id.length() - 1);
        }/*  w  w  w. ja va  2s.  c  o m*/
        id = id.replaceAll("\\\\", "_");
        id = id.replaceAll("/", "_");
        String filename = archiveto + "/" + id + ".eml";
        String txtname = archiveto + "/" + id + ".txt";
        File file = new File(filename);
        File txtfile = new File(txtname);
        //Only if spool file does not exists
        if (!file.exists()) {

            String emailfrom = "nomail@nodomain.it";
            Address a[] = msg.getFrom();
            if (a != null && a.length > 0) {
                InternetAddress sender = ((InternetAddress) a[0]);
                emailfrom = sender.getAddress();
            }
            String emailto = "nomail@nodomain.it";
            a = msg.getRecipients(Message.RecipientType.TO);
            if (a != null && a.length > 0) {
                InternetAddress to = ((InternetAddress) a[0]);
                emailto = to.getAddress();
            }
            String subject = msg.getSubject();
            java.util.Date date = msg.getReceivedDate();
            java.util.Calendar cal = java.util.Calendar.getInstance();
            cal.setTime(date);
            int dd = cal.get(java.util.Calendar.DAY_OF_MONTH);
            int mm = cal.get(java.util.Calendar.MONTH) + 1;
            int yyyy = cal.get(java.util.Calendar.YEAR);
            String sdd = dd < 10 ? "0" + dd : "" + dd;
            String smm = mm < 10 ? "0" + mm : "" + mm;
            String syyyy = "" + yyyy;

            FileOutputStream fos = new FileOutputStream(file);
            msg.writeTo(fos);
            fos.close();

            PrintWriter pw = new PrintWriter(txtfile);
            pw.println(emailfrom);
            pw.println(emailto);
            pw.println(subject);
            pw.println(sdd + "/" + smm + "/" + syyyy);
            pw.println(profile.getUserId());
            pw.println(idcategory);
            pw.println(idsubcategory);
            pw.close();
        }
    }
    from.markDmsArchivedMessages(nuids, fullthreads);
}

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

public void processViewAttachment(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 pcid = request.getParameter("cid");
    String purl = request.getParameter("url");
    String punknown = request.getParameter("unknown");

    try {/*from   w  ww  .j a  v a2  s  . co m*/
        account.checkStoreConnected();
        FolderCache mcache = null;
        Message m = null;
        if (providername == null) {
            mcache = account.getFolderCache(pfoldername);
            long newmsguid = Long.parseLong(puidmessage);
            m = mcache.getMessage(newmsguid);
        } else {
            mcache = fcProvided;
            m = mcache.getProvidedMessage(providername, providerid);
        }
        HTMLMailData mailData = mcache.getMailData((MimeMessage) m);
        Part part = null;
        if (pcid != null) {
            part = mailData.getCidPart(pcid);
        } else if (purl != null) {
            part = mailData.getUrlPart(purl);
        } else if (pidattach != null) {
            part = mailData.getAttachmentPart(Integer.parseInt(pidattach));
        } else if (punknown != null) {
            part = mailData.getUnknownPart(Integer.parseInt(punknown));
        }

        if (part != null) {
            String name = part.getFileName();
            if (name == null)
                name = "";
            try {
                name = MailUtils.decodeQString(name);
            } catch (Exception exc) {
            }
            name = name.trim();
            if (providername == null) {
                Folder folder = mailData.getFolder();
                if (!folder.isOpen())
                    folder.open(Folder.READ_ONLY);
            }

            String fileHash = AlgoUtils.md5Hex(new CompositeId(pfoldername, puidmessage, pidattach).toString());
            long lastModified = m.getReceivedDate().getTime();
            AttachmentViewerDocumentHandler docHandler = new AttachmentViewerDocumentHandler(false,
                    getEnv().getProfileId(), fileHash, part, lastModified);
            DocEditorManager.DocumentConfig config = getWts().prepareDocumentEditing(docHandler, name,
                    lastModified);

            new JsonResult(config).printTo(out);

        }
    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
    }
}

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

public void processPortletMail(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    ArrayList<JsPreviewMessage> items = new ArrayList<>();

    try {/*from w ww. j  a va2  s.  c o m*/
        MailAccount account = getAccount(request);
        String query = ServletUtils.getStringParameter(request, "query", null);
        int visibleRows = 0;
        int maxVisibleRows = 20;

        if (query == null) {
            String folderId = account.getInboxFolderFullName();
            FolderCache fc = account.getFolderCache(folderId);
            Message msgs[] = fc.getMessages(FolderCache.SORT_BY_DATE, false, true, -1, true, false, null,
                    false);
            if (msgs != null)
                fc.fetch(msgs, getMessageFetchProfile(), 0, 50);
            else
                msgs = new Message[0];

            for (Message msg : msgs) {
                SonicleIMAPMessage simsg = (SonicleIMAPMessage) msg;

                InternetAddress iafrom = null;
                Address vfrom[] = msg.getFrom();
                if (vfrom != null && vfrom.length > 0) {
                    Address afrom = vfrom[0];
                    if (afrom instanceof InternetAddress) {
                        iafrom = (InternetAddress) afrom;
                    }
                }

                Address[] rcpts = msg.getRecipients(Message.RecipientType.TO);
                ArrayList<InternetAddress> tos = new ArrayList<>();
                if (rcpts != null)
                    for (Address ato : rcpts) {
                        if (ato instanceof InternetAddress) {
                            InternetAddress iato = (InternetAddress) ato;
                            tos.add(iato);
                        }
                    }

                String msgtext = "";
                if (visibleRows < maxVisibleRows) {
                    msgtext = MailUtils.peekText(simsg);
                    if (msgtext == null)
                        msgtext = "";
                    else {
                        msgtext = msgtext.trim();
                        if (msgtext.length() > 100)
                            msgtext = msgtext.substring(0, 100);
                    }
                    ++visibleRows;
                }

                String from = iafrom != null
                        ? (iafrom.getPersonal() != null ? iafrom.getPersonal() : iafrom.getAddress())
                        : "";
                String to = "";
                if (tos.size() > 0) {
                    boolean first = true;
                    for (InternetAddress iato : tos) {
                        if (!first)
                            to += "; ";
                        to += (iato.getPersonal() != null ? iato.getPersonal() : iato.getAddress());
                        first = false;
                    }
                }

                JsPreviewMessage jsmsg = new JsPreviewMessage(simsg.getUID(), folderId,
                        getInternationalFolderName(account.getFolderCache(folderId)), simsg.getSubject(), from,
                        to, msg.getReceivedDate(), msgtext);
                items.add(jsmsg);
            }
        } else {
        }

        new JsonResult(items).printTo(out);

    } catch (Exception ex) {
        logger.error("Error in PortletMail", ex);
        new JsonResult(false, "Error").printTo(out);
    }
}