Example usage for javax.mail Message getSubject

List of usage examples for javax.mail Message getSubject

Introduction

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

Prototype

public abstract String getSubject() throws MessagingException;

Source Link

Document

Get the subject of this message.

Usage

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

/**
 * recursively processes attachments, fetching and saving it if needed
 * parses the given part p, and adds it to hte attachmentsList.
 * in some cases, like a text/html type without a filename, we instead append it to the textlist
 * @throws MessagingException/* w  ww  .  j  ava 2  s .com*/
 */
private void handleAttachments(int idx, Message m, Part p, List<String> textList, List<Blob> attachmentsList)
        throws MessagingException {
    String ct = null;
    if (!(m instanceof MimeMessage)) {
        Exception e = new IllegalArgumentException("Not a MIME message!");
        e.fillInStackTrace();
        log.warn(Util.stackTrace(e));
        return;
    }

    String filename = null;
    try {
        filename = p.getFileName();
    } catch (Exception e) {
        // seen this happen with:
        // Folders__gmail-sent Message #12185 Expected ';', got "Message"
        // javax.mail.internet.ParseException: Expected ';', got "Message"

        dataErrors.add("Unable to read attachment name: " + folder_name() + " Message# " + idx);
        return;
    }

    String sanitizedFName = Util.sanitizeFolderName(emailStore.getAccountID() + "." + folder_name());
    if (filename == null) {
        String tempFname = sanitizedFName + "." + idx;
        dataErrors.add("attachment filename is null for " + sanitizedFName + " Message#" + idx
                + " assigning it the name: " + tempFname);
        if (p.isMimeType("text/html")) {
            try {
                log.info("Turning message " + sanitizedFName + " Message#" + idx
                        + " into text although it is an attachment");
                String html = (String) p.getContent();
                String text = Util.unescapeHTML(html);
                org.jsoup.nodes.Document doc = Jsoup.parse(text);

                StringBuilder sb = new StringBuilder();
                HTMLUtils.extractTextFromHTML(doc.body(), sb);
                textList.add(sb.toString());
                return;
            } catch (Exception e) {
                Util.print_exception("Error reading contents of text/html multipart without a filename!", e,
                        log);
                return;
            }
        }
        filename = tempFname;
    }

    // Replacing any of the disallowed filename characters (\/:*?"<>|&) to _
    // (note: & causes problems with URLs for serveAttachment etc, so it's also replaced)
    String newFilename = Util.sanitizeFileName(filename);

    // Updating filename if it's changed after sanitizing.
    if (!newFilename.equals(filename)) {
        log.info("Filename changed from " + filename + " to " + newFilename);
        filename = newFilename;
    }

    try {
        ct = p.getContentType();
        if (filename.indexOf(".") < 0) // no ext in filename... let's fix it if possible
        {
            // Using startsWith instead of equals because sometimes the ct has crud beyond the image/jpeg;...crud....
            // Below are the most common file types, more type can be added if needed

            // Most common APPLICATION TYPE
            if (ct.startsWith("application/pdf"))
                filename = filename + ".pdf";
            if (ct.startsWith("application/zip"))
                filename = filename + ",zip";
            // Most common IMAGE TYPE
            if (ct.startsWith("image/jpeg"))
                filename = filename + ".jpg";
            if (ct.startsWith("image/gif"))
                filename = filename + ".gif";
            if (ct.startsWith("image/png"))
                filename = filename + ".png";
            // Most Common VIDEO TYPE
            if (ct.startsWith("video/x-ms-wmv"))
                filename = filename + ".wmv";
            // Most Common AUDIO TYPE
            if (ct.startsWith("audio/mpeg"))
                filename = filename + ".mp3";
            if (ct.startsWith("audio/mp4"))
                filename = filename + ".mp4";
            // Most Common TEXT TYPE
            if (ct.startsWith("text/html"))
                filename = filename + ".html";
            // Windows Office
            if (ct.startsWith("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) //Word
                filename = filename + ".docx";
            if (ct.startsWith("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) //Excel
                filename = filename + ".xlsx";
            if (ct.startsWith("application/vnd.openxmlformats-officedocument.presentationml.presentation")) //PowerPoint
                filename = filename + ".pptx";
        }
        // retain only up to first semi-colon; often ct is something like text/plain; name="filename"' we don't want to log the filename
        int x = ct.indexOf(";");
        if (x >= 0)
            ct = ct.substring(0, x);
        log.info("Attachment content type: " + ct + " filename = " + Util.blurKeepingExtension(filename));
    } catch (Exception pex) {
        dataErrors.add("Can't read CONTENT-TYPE: " + ct + " filename:" + filename + " size = " + p.getSize()
                + " subject: " + m.getSubject() + " Date : " + m.getSentDate().toString() + "\n Exception: "
                + pex + "\n" + Util.stackTrace(pex));
        return;
    }

    //       if (filename == null && !p.isMimeType("text/html") && !p.isMimeType("message/partial")) // expected not to have a filename with mime type text/html
    //          log.warn ("Attachment filename is null: " + Util.stackTrace());

    boolean success = true;
    // the size passed in here is the part size, which is not really the binary blob size.
    // when we read the stream below in blobStore.add(), we'll set it again to the binary blob size
    Blob b = new EmailAttachmentBlob(filename, p.getSize(), (MimeMessage) m, p);

    if (fetchConfig.downloadAttachments) {
        // this containment check is only on the basis of file name and size currently,
        // not on the actual hash
        if (archive.getBlobStore().contains(b)) {
            log.debug("Cache hit! " + b);
        } else {
            try {
                if (filename.endsWith(".tif"))
                    log.info("Fetching attachment..." + Util.blurKeepingExtension(filename));

                // performance critical! use large buffer! currently 256KB
                // stream will be closed by callee

                long start = System.currentTimeMillis();
                long nBytes = archive.getBlobStore().add(b,
                        new BufferedInputStream(p.getInputStream(), 256 * 1024));
                long end = System.currentTimeMillis();
                if (nBytes != -1) {
                    long diff = end - start;
                    String s = "attachment size " + nBytes + " bytes, fetched in " + diff + " millis";
                    if (diff > 0)
                        s += " (" + (nBytes / diff) + " KB/s)";
                    log.info(s);
                }

                Util.ASSERT(archive.getBlobStore().contains(b));

            } catch (IOException ioe) {
                success = false;
                dataErrors.add("WARNING: Unable to fetch attachment: filename: " + filename + " size = "
                        + p.getSize() + " subject: " + m.getSubject() + " Date : " + m.getSentDate().toString()
                        + "\nException: " + ioe);
                ioe.printStackTrace(System.out);
            }
        }

        if (success) {
            attachmentsList.add(b);

            /// generate thumbnail only if not already cached
            try {
                archive.getBlobStore().generate_thumbnail(b); // supplement
            } catch (IOException ioe) {
                log.warn("failed to create thumbnail, filename: " + filename + " size = " + p.getSize()
                        + " subject: " + m.getSubject() + " Date : " + m.getSentDate().toString()
                        + "\nException: " + ioe);
                ioe.printStackTrace(System.out);
            }
        }
    }
}

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

private Sequence getMessageListAsXML(Sequence[] args, Sequence contextSequence) throws XPathException {
    Message[] msgList;// w  ww. ja  v a 2  s.  c o  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: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  ww . ja  v a  2  s.  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 processSaveMail(HttpServletRequest request, HttpServletResponse response) {
    MailAccount account = getAccount(request);
    String foldername = request.getParameter("folder");
    String uid = request.getParameter("id");

    try {/*from  w  w w  .  j  a  v a  2 s  . co m*/
        account.checkStoreConnected();
        FolderCache mcache = account.getFolderCache(foldername);
        Message msg = mcache.getMessage(Long.parseLong(uid));
        String subject = msg.getSubject();
        ServletUtils.setFileStreamHeadersForceDownload(response, subject + ".eml");
        OutputStream out = response.getOutputStream();
        msg.writeTo(out);
    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
    }
}

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

public void processAttachFromMessages(HttpServletRequest request, HttpServletResponse response,
        PrintWriter out) {/*from   ww w  .  j av  a2s  .c om*/
    try {
        MailAccount account = getAccount(request);
        account.checkStoreConnected();

        String tag = request.getParameter("tag");
        String pfoldername = request.getParameter("folder");
        String suids[] = request.getParameterValues("ids");
        String multifolder = request.getParameter("multifolder");
        boolean mf = multifolder != null && multifolder.equals("true");

        String ctype = "message/rfc822";

        ArrayList<WebTopSession.UploadedFile> ufiles = new ArrayList<>();
        for (String suid : suids) {
            String foldername = pfoldername;

            if (mf) {
                int ix = suid.indexOf("|");
                foldername = suid.substring(0, ix);
                suid = suid.substring(ix + 1);
            }
            long uid = Long.parseLong(suid);
            FolderCache mcache = account.getFolderCache(foldername);

            Message msg = mcache.getMessage(uid);
            File file = WT.createTempFile();
            FileOutputStream fos = new FileOutputStream(file);
            msg.writeTo(fos);
            fos.close();
            long filesize = file.length();
            String filename = msg.getSubject() + ".eml";

            WebTopSession.UploadedFile uploadedFile = new WebTopSession.UploadedFile(false, this.SERVICE_ID,
                    file.getName(), tag, filename, filesize, ctype);
            environment.getSession().addUploadedFile(uploadedFile);
            ufiles.add(uploadedFile);
        }

        MapItemList data = new MapItemList();
        for (WebTopSession.UploadedFile ufile : ufiles) {
            MapItem mi = new MapItem();
            mi.add("uploadId", ufile.getUploadId());
            mi.add("name", ufile.getFilename());
            mi.add("size", ufile.getSize());
            mi.add("editable", isFileEditableInDocEditor(ufile.getFilename()));
            data.add(mi);
        }
        new JsonResult(data).printTo(out);
    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
        new JsonResult(false, exc.getMessage()).printTo(out);
    }
}

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

private String getForwardBody(Message msg, String body, int format, boolean isHtml, String fromtitle,
        String totitle, String cctitle, String datetitle, String subjecttitle) throws MessagingException {
    UserProfile profile = environment.getProfile();
    Locale locale = profile.getLocale();
    String msgSubject = msg.getSubject();
    if (msgSubject == null) {
        msgSubject = "";
    }// w  w  w .  j av a  2s.com
    msgSubject = MailUtils.htmlescape(msgSubject);
    Address ad[] = msg.getFrom();
    String msgFrom = "";
    if (ad != null) {
        msgFrom = isHtml ? getHTMLDecodedAddress(ad[0]) : getDecodedAddress(ad[0]);
    }
    java.util.Date dt = msg.getSentDate();
    String msgDate = "";
    if (dt != null) {
        msgDate = DateFormat.getDateTimeInstance(java.text.DateFormat.LONG, java.text.DateFormat.LONG, locale)
                .format(dt);
    }
    ad = msg.getRecipients(Message.RecipientType.TO);
    String msgTo = null;
    if (ad != null) {
        msgTo = "";
        for (int j = 0; j < ad.length; ++j) {
            msgTo += isHtml ? getHTMLDecodedAddress(ad[j]) : getDecodedAddress(ad[j]) + " ";
        }
    }
    ad = msg.getRecipients(Message.RecipientType.CC);
    String msgCc = null;
    if (ad != null) {
        msgCc = "";
        for (int j = 0; j < ad.length; ++j) {
            msgCc += isHtml ? getHTMLDecodedAddress(ad[j]) : getDecodedAddress(ad[j]) + " ";
        }
    }

    StringBuffer sb = new StringBuffer();
    String cr = "\n";
    if (format != SimpleMessage.FORMAT_TEXT) {
        cr = "<BR>";
    }
    if (format != SimpleMessage.FORMAT_HTML) {
        if (format == SimpleMessage.FORMAT_PREFORMATTED) {
            sb.append("<TT>");
        }
        sb.append(cr + cr + cr
                + "----------------------------------------------------------------------------------" + cr
                + cr);
        sb.append(fromtitle + ": " + msgFrom + cr);
        if (msgTo != null) {
            sb.append(totitle + ": " + msgTo + cr);
        }
        if (msgCc != null) {
            sb.append(cctitle + ": " + msgCc + cr);
        }
        sb.append(datetitle + ": " + msgDate + cr);
        sb.append(subjecttitle + ": " + msgSubject + cr + cr);
        if (format == SimpleMessage.FORMAT_PREFORMATTED) {
            sb.append("</TT>");
        }
    } else {
        sb.append(cr + "<HR>" + cr + cr);
        sb.append("<font face='Arial, Helvetica, sans-serif' size=2>");
        sb.append("<B>" + fromtitle + ":</B> " + msgFrom + "<BR>");
        if (msgTo != null) {
            sb.append("<B>" + totitle + ":</B> " + msgTo + "<BR>");
        }
        if (msgCc != null) {
            sb.append("<B>" + cctitle + ":</B> " + msgCc + "<BR>");
        }
        sb.append("<B>" + datetitle + ":</B> " + msgDate + "<BR>");
        sb.append("<B>" + subjecttitle + ":</B> " + msgSubject + "<BR>");
        sb.append("</font><br>" + cr);
    }

    // Prepend "> " for each line in the body
    //
    if (body != null) {
        if (format == SimpleMessage.FORMAT_HTML) {
            //        sb.append("<TABLE border=0 width='100%'><TR><td width=2 bgcolor=#000088></td><td width=2></td><td>");
            //        sb.append("<BLOCKQUOTE style='BORDER-LEFT: #000080 2px solid; MARGIN-LEFT: 5px; PADDING-LEFT: 5px'>");
        }
        if (!isHtml) {
            if (format == SimpleMessage.FORMAT_PREFORMATTED) {
                //          sb.append("<BLOCKQUOTE style='BORDER-LEFT: #000080 2px solid; MARGIN-LEFT: 5px; PADDING-LEFT: 5px'>");
                sb.append("<tt>");
            }
            StringTokenizer st = new StringTokenizer(body, "\n", true);
            while (st.hasMoreTokens()) {
                String token = st.nextToken();
                if (token.equals("\n")) {
                    sb.append(cr);
                } else {
                    if (format == SimpleMessage.FORMAT_TEXT) {
                        sb.append("> ");
                    }
                    //sb.append(MailUtils.htmlescape(token));
                    sb.append(token);
                }
            }
            if (format == SimpleMessage.FORMAT_PREFORMATTED) {
                sb.append("</tt>");
                //          sb.append("</BLOCKQUOTE>");
            }
        } else {
            //sb.append(getBodyInnerHtml(body));
            sb.append(body);
        }
        if (format == SimpleMessage.FORMAT_HTML) {
            //        sb.append("</td></tr></table>");
            //        sb.append("</BLOCKQUOTE>");
        }
    }
    return sb.toString();
}

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

private String getReplyBody(Message msg, String body, int format, boolean isHtml, String fromtitle,
        String totitle, String cctitle, String datetitle, String subjecttitle, ArrayList<String> attnames)
        throws MessagingException {
    UserProfile profile = environment.getProfile();
    Locale locale = profile.getLocale();
    String msgSubject = msg.getSubject();
    if (msgSubject == null) {
        msgSubject = "";
    }/*from   w  w  w . j  av  a 2s  .c  o m*/
    msgSubject = MailUtils.htmlescape(msgSubject);
    Address ad[] = msg.getFrom();
    String msgFrom = "";
    if (ad != null) {
        msgFrom = isHtml ? getHTMLDecodedAddress(ad[0]) : getDecodedAddress(ad[0]);
    }
    java.util.Date dt = msg.getSentDate();
    String msgDate = "";
    if (dt != null) {
        msgDate = DateFormat.getDateTimeInstance(java.text.DateFormat.LONG, java.text.DateFormat.LONG, locale)
                .format(dt);
    }
    ad = msg.getRecipients(Message.RecipientType.TO);
    String msgTo = null;
    if (ad != null) {
        msgTo = "";
        for (int j = 0; j < ad.length; ++j) {
            msgTo += isHtml ? getHTMLDecodedAddress(ad[j]) : getDecodedAddress(ad[j]) + " ";
        }
    }
    ad = msg.getRecipients(Message.RecipientType.CC);
    String msgCc = null;
    if (ad != null) {
        msgCc = "";
        for (int j = 0; j < ad.length; ++j) {
            msgCc += isHtml ? getHTMLDecodedAddress(ad[j]) : getDecodedAddress(ad[j]) + " ";
        }
    }

    //
    /*String sfrom = "";
    try {
       if (msg.getFrom() != null) {
    InternetAddress ia = (InternetAddress) msg.getFrom()[0];
    String personal = ia.getPersonal();
    String mail = ia.getAddress();
    if (personal == null || personal.equals(mail)) {
       sfrom = mail;
    } else {
       sfrom = personal + " <" + mail + ">";
    }
       }
    } catch (Exception exc) {
               
    }*/
    StringBuffer sb = new StringBuffer();
    String cr = "\n";
    if (format != SimpleMessage.FORMAT_TEXT) {
        cr = "<BR>";
    }
    if (format != SimpleMessage.FORMAT_HTML) {
        if (format == SimpleMessage.FORMAT_PREFORMATTED) {
            sb.append("<TT>");
        }
        sb.append(cr + cr + cr
                + "----------------------------------------------------------------------------------" + cr
                + cr);
        sb.append(fromtitle + ": " + msgFrom + cr);
        if (msgTo != null) {
            sb.append(totitle + ": " + msgTo + cr);
        }
        if (msgCc != null) {
            sb.append(cctitle + ": " + msgCc + cr);
        }
        sb.append(datetitle + ": " + msgDate + cr);
        sb.append(subjecttitle + ": " + msgSubject + cr + cr);
        if (format == SimpleMessage.FORMAT_PREFORMATTED) {
            sb.append("</TT>");
        }
    } else {
        sb.append(cr + "<HR>" + cr + cr);
        sb.append("<font face='Arial, Helvetica, sans-serif' size=2>");
        sb.append("<B>" + fromtitle + ":</B> " + msgFrom + "<BR>");
        if (msgTo != null) {
            sb.append("<B>" + totitle + ":</B> " + msgTo + "<BR>");
        }
        if (msgCc != null) {
            sb.append("<B>" + cctitle + ":</B> " + msgCc + "<BR>");
        }
        sb.append("<B>" + datetitle + ":</B> " + msgDate + "<BR>");
        sb.append("<B>" + subjecttitle + ":</B> " + msgSubject + "<BR>");
        sb.append("</font><br>" + cr);
    }

    // Prepend "> " for each line in the body
    //
    if (body != null) {
        if (format == SimpleMessage.FORMAT_HTML) {
            //        sb.append("<TABLE border=0 width='100%'><TR><td width=2 bgcolor=#000088></td><td width=2></td><td>");
            sb.append(
                    "<BLOCKQUOTE style='BORDER-LEFT: #000080 2px solid; MARGIN-LEFT: 5px; PADDING-LEFT: 5px'>");
        }
        if (!isHtml) {
            if (format == SimpleMessage.FORMAT_PREFORMATTED) {
                sb.append(
                        "<BLOCKQUOTE style='BORDER-LEFT: #000080 2px solid; MARGIN-LEFT: 5px; PADDING-LEFT: 5px'>");
                sb.append("<tt>");
            }
            StringTokenizer st = new StringTokenizer(body, "\n", true);
            while (st.hasMoreTokens()) {
                String token = st.nextToken();
                if (token.equals("\n")) {
                    sb.append(cr);
                } else {
                    if (format == SimpleMessage.FORMAT_TEXT) {
                        sb.append("> ");
                    }
                    //sb.append(MailUtils.htmlescape(token));
                    sb.append(token);
                }
            }
            if (format == SimpleMessage.FORMAT_PREFORMATTED) {
                sb.append("</tt>");
                sb.append("</BLOCKQUOTE>");
            }
        } else {
            /*
            //String ubody = body.toUpperCase();
            while (true) {
               int ix1 = StringUtils.indexOfIgnoreCase(body,"<BODY");
               if (ix1 < 0) {
                  break;
               }
               int ix2 = StringUtils.indexOfIgnoreCase(body,">", ix1 + 1);
               if (ix2 < 0) {
                  ix2 = ix1 + 4;
               }
               int ix3 = StringUtils.indexOfIgnoreCase(body,"</BODY", ix2 + 1);
               if (ix3 > 0) {
                  body = body.substring(ix2 + 1, ix3);
               } else {
                  body = body.substring(ix2 + 1);
               }
            }
            //body=removeStartEndTag(body,unwantedTags);
            */

            sb.append(body);
        }
        htmlAppendAttachmentNames(sb, attnames);
        if (format == SimpleMessage.FORMAT_HTML) {
            //        sb.append("</td></tr></table>");
            sb.append("</BLOCKQUOTE>");
        }
    }
    return sb.toString();
}

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

public void processGetAttachments(HttpServletRequest request, HttpServletResponse response) {
    MailAccount account = getAccount(request);
    String pfoldername = request.getParameter("folder");
    String puidmessage = request.getParameter("idmessage");
    String pids[] = request.getParameterValues("ids");
    String providername = request.getParameter("provider");
    String providerid = request.getParameter("providerid");

    try {/*  w w  w .j av 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);
        String name = m.getSubject();
        if (name == null) {
            name = "attachments";
        }
        try {
            name = MailUtils.decodeQString(name);
        } catch (Exception exc) {
        }
        name += ".zip";
        //prepare hashmap to hold already used pnames
        HashMap<String, String> pnames = new HashMap<String, String>();
        ServletUtils.setFileStreamHeaders(response, "application/x-zip-compressed", DispositionType.INLINE,
                name);
        JarOutputStream jos = new java.util.jar.JarOutputStream(response.getOutputStream());
        byte[] b = new byte[64 * 1024];
        for (String pid : pids) {
            Part part = mailData.getAttachmentPart(Integer.parseInt(pid));
            String pname = part.getFileName();
            if (pname == null) {
                pname = "unknown";
            }
            /*
            try {
               pname = MailUtils.decodeQString(pname, "iso-8859-1");
            } catch (Exception exc) {
            }
            */
            //keep name and extension
            String bpname = pname;
            String extpname = null;
            int ix = pname.lastIndexOf(".");
            if (ix > 0) {
                bpname = pname.substring(0, ix);
                extpname = pname.substring(ix + 1);
            }
            //check for existing pname and find an unused name
            int xid = 0;
            String rpname = pname;
            while (pnames.containsKey(rpname)) {
                rpname = bpname + " (" + (++xid) + ")";
                if (extpname != null)
                    rpname += "." + extpname;
            }

            JarEntry je = new JarEntry(rpname);
            jos.putNextEntry(je);
            if (providername == null) {
                Folder folder = mailData.getFolder();
                if (!folder.isOpen()) {
                    folder.open(Folder.READ_ONLY);
                }
            }
            InputStream is = part.getInputStream();
            int len = 0;
            while ((len = is.read(b)) != -1) {
                jos.write(b, 0, len);
            }
            is.close();

            //remember used pname
            pnames.put(rpname, rpname);
        }
        jos.closeEntry();
        jos.flush();
        jos.close();

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

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

public Message createMessage(String from, SimpleMessage smsg, List<JsAttachment> attachments, boolean tosave)
        throws Exception {
    MimeMessage msg = null;//from   w w w  .j  a  va  2  s  .c o m
    boolean success = true;

    String[] to = SimpleMessage.breakAddr(smsg.getTo());
    String[] cc = SimpleMessage.breakAddr(smsg.getCc());
    String[] bcc = SimpleMessage.breakAddr(smsg.getBcc());
    String replyTo = smsg.getReplyTo();

    msg = new MimeMessage(mainAccount.getMailSession());
    msg.setFrom(getInternetAddress(from));
    InternetAddress ia = null;

    //set the TO recipient
    for (int q = 0; q < to.length; q++) {
        //        Service.logger.debug("to["+q+"]="+to[q]);
        to[q] = to[q].replace(',', ' ');
        try {
            ia = getInternetAddress(to[q]);
        } catch (AddressException exc) {
            throw new AddressException(to[q]);
        }
        msg.addRecipient(Message.RecipientType.TO, ia);
    }

    //set the CC recipient
    for (int q = 0; q < cc.length; q++) {
        cc[q] = cc[q].replace(',', ' ');
        try {
            ia = getInternetAddress(cc[q]);
        } catch (AddressException exc) {
            throw new AddressException(cc[q]);
        }
        msg.addRecipient(Message.RecipientType.CC, ia);
    }

    //set BCC recipients
    for (int q = 0; q < bcc.length; q++) {
        bcc[q] = bcc[q].replace(',', ' ');
        try {
            ia = getInternetAddress(bcc[q]);
        } catch (AddressException exc) {
            throw new AddressException(bcc[q]);
        }
        msg.addRecipient(Message.RecipientType.BCC, ia);
    }

    //set reply to addr
    if (replyTo != null && replyTo.length() > 0) {
        Address[] replyaddr = new Address[1];
        replyaddr[0] = getInternetAddress(replyTo);
        msg.setReplyTo(replyaddr);
    }

    //add any header
    String headerLines[] = smsg.getHeaderLines();
    for (int i = 0; i < headerLines.length; ++i) {
        if (!headerLines[i].startsWith("Sonicle-reply-folder")) {
            msg.addHeaderLine(headerLines[i]);
        }
    }

    //add reply/references
    String inreplyto = smsg.getInReplyTo();
    String references[] = smsg.getReferences();
    String replyfolder = smsg.getReplyFolder();
    if (inreplyto != null) {
        msg.setHeader("In-Reply-To", inreplyto);
    }
    if (references != null && references[0] != null) {
        msg.setHeader("References", references[0]);
    }
    if (tosave) {
        if (replyfolder != null) {
            msg.setHeader("Sonicle-reply-folder", replyfolder);
        }
        msg.setHeader("Sonicle-draft", "true");
    }

    //add forward data
    String forwardedfrom = smsg.getForwardedFrom();
    String forwardedfolder = smsg.getForwardedFolder();
    if (forwardedfrom != null) {
        msg.setHeader("Forwarded-From", forwardedfrom);
    }
    if (tosave) {
        if (forwardedfolder != null) {
            msg.setHeader("Sonicle-forwarded-folder", forwardedfolder);
        }
        msg.setHeader("Sonicle-draft", "true");
    }
    //set the subject
    String subject = smsg.getSubject();
    try {
        //subject=MimeUtility.encodeText(smsg.getSubject(), "ISO-8859-1", null);
        subject = MimeUtility.encodeText(smsg.getSubject());
    } catch (Exception exc) {
    }
    msg.setSubject(subject);

    //set priority
    int priority = smsg.getPriority();
    if (priority != 3) {
        msg.setHeader("X-Priority", "" + priority);

        //set receipt
    }
    String receiptTo = from;
    try {
        receiptTo = MimeUtility.encodeText(from, "ISO-8859-1", null);
    } catch (Exception exc) {
    }
    if (smsg.getReceipt()) {
        msg.setHeader("Disposition-Notification-To", from);

        //see if there are any new attachments for the message
    }
    int noAttach;
    int newAttach;

    if (attachments == null) {
        newAttach = 0;
    } else {
        newAttach = attachments.size();
    }

    //get the array of the old attachments
    Part[] oldParts = smsg.getAttachments();

    //check if there are old attachments
    if (oldParts == null) {
        noAttach = 0;
    } else { //old attachments exist
        noAttach = oldParts.length;
    }

    if ((newAttach > 0) || (noAttach > 0) || !smsg.getMime().equalsIgnoreCase("text/plain")) {
        // create the main Multipart
        MimeMultipart mp = new MimeMultipart("mixed");
        MimeMultipart unrelated = null;

        String textcontent = smsg.getTextContent();
        //if is text, or no alternative text is available, add the content as one single body part
        //else create a multipart/alternative with both rich and text mime content
        if (textcontent == null || smsg.getMime().equalsIgnoreCase("text/plain")) {
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8"));
            mp.addBodyPart(mbp1);
        } else {
            MimeMultipart alternative = new MimeMultipart("alternative");
            //the rich part
            MimeBodyPart mbp2 = new MimeBodyPart();
            mbp2.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8"));
            //the text part
            MimeBodyPart mbp1 = new MimeBodyPart();

            /*          ByteArrayOutputStream bos=new ByteArrayOutputStream(textcontent.length());
             com.sun.mail.util.QPEncoderStream qpe=new com.sun.mail.util.QPEncoderStream(bos);
             for(int i=0;i<textcontent.length();++i) {
             try {
             qpe.write(textcontent.charAt(i));
             } catch(IOException exc) {
             Service.logger.error("Exception",exc);
             }
             }
             textcontent=new String(bos.toByteArray());*/
            mbp1.setContent(textcontent, MailUtils.buildPartContentType("text/plain", "UTF-8"));
            //          mbp1.setHeader("Content-transfer-encoding","quoted-printable");

            alternative.addBodyPart(mbp1);
            alternative.addBodyPart(mbp2);

            MimeBodyPart altbody = new MimeBodyPart();
            altbody.setContent(alternative);

            mp.addBodyPart(altbody);
        }

        if (noAttach > 0) { //if there are old attachments
            // create the parts with the attachments
            //MimeBodyPart[] mbps2 = new MimeBodyPart[noAttach];
            //Part[] mbps2 = new Part[noAttach];

            //for(int e = 0;e < noAttach;e++) {
            //  mbps2[e] = (Part)oldParts[e];
            //}//end for e
            //add the old attachment parts
            for (int r = 0; r < noAttach; r++) {
                Object content = null;
                String contentType = null;
                String contentFileName = null;
                if (oldParts[r] instanceof Message) {
                    //                Service.logger.debug("Attachment is a message");
                    Message msgpart = (Message) oldParts[r];
                    MimeMessage mm = new MimeMessage(mainAccount.getMailSession());
                    mm.addFrom(msgpart.getFrom());
                    mm.setRecipients(Message.RecipientType.TO, msgpart.getRecipients(Message.RecipientType.TO));
                    mm.setRecipients(Message.RecipientType.CC, msgpart.getRecipients(Message.RecipientType.CC));
                    mm.setRecipients(Message.RecipientType.BCC,
                            msgpart.getRecipients(Message.RecipientType.BCC));
                    mm.setReplyTo(msgpart.getReplyTo());
                    mm.setSentDate(msgpart.getSentDate());
                    mm.setSubject(msgpart.getSubject());
                    mm.setContent(msgpart.getContent(), msgpart.getContentType());
                    content = mm;
                    contentType = "message/rfc822";
                } else {
                    //                Service.logger.debug("Attachment is not a message");
                    content = oldParts[r].getContent();
                    if (!(content instanceof MimeMultipart)) {
                        contentType = oldParts[r].getContentType();
                        contentFileName = oldParts[r].getFileName();
                    }
                }
                MimeBodyPart mbp = new MimeBodyPart();
                if (contentFileName != null) {
                    mbp.setFileName(contentFileName);
                    //              Service.logger.debug("adding attachment mime "+contentType+" filename "+contentFileName);
                    contentType += "; name=\"" + contentFileName + "\"";
                }
                if (content instanceof MimeMultipart)
                    mbp.setContent((MimeMultipart) content);
                else
                    mbp.setDataHandler(new DataHandler(content, contentType));
                mp.addBodyPart(mbp);
            }

        } //end if, adding old attachments

        if (newAttach > 0) { //if there are new attachments
            // create the parts with the attachments
            MimeBodyPart[] mbps = new MimeBodyPart[newAttach];

            for (int e = 0; e < newAttach; e++) {
                mbps[e] = new MimeBodyPart();

                // attach the file to the message
                JsAttachment attach = (JsAttachment) attachments.get(e);
                UploadedFile upfile = getUploadedFile(attach.uploadId);
                FileDataSource fds = new FileDataSource(upfile.getFile());
                mbps[e].setDataHandler(new DataHandler(fds));
                // filename starts has format:
                // "_" + userid + sessionId + "_" + filename
                //
                if (attach.inline) {
                    mbps[e].setDisposition(Part.INLINE);
                }
                String contentFileName = attach.fileName.trim();
                mbps[e].setFileName(contentFileName);
                String contentType = upfile.getMediaType() + "; name=\"" + contentFileName + "\"";
                mbps[e].setHeader("Content-type", contentType);
                if (attach.cid != null && attach.cid.trim().length() > 0) {
                    mbps[e].setHeader("Content-ID", "<" + attach.cid + ">");
                    mbps[e].setHeader("X-Attachment-Id", attach.cid);
                    mbps[e].setDisposition(Part.INLINE);
                    if (unrelated == null)
                        unrelated = new MimeMultipart("mixed");
                }
            } //end for e

            //add the new attachment parts
            if (unrelated == null) {
                for (int r = 0; r < newAttach; r++)
                    mp.addBodyPart(mbps[r]);
            } else {
                //mp becomes the related part with text parts and cids
                MimeMultipart related = mp;
                related.setSubType("related");
                //nest the related part into the mixed part
                mp = unrelated;
                MimeBodyPart mbd = new MimeBodyPart();
                mbd.setContent(related);
                mp.addBodyPart(mbd);
                for (int r = 0; r < newAttach; r++) {
                    if (mbps[r].getHeader("Content-ID") != null) {
                        related.addBodyPart(mbps[r]);
                    } else {
                        mp.addBodyPart(mbps[r]);
                    }
                }
            }

        } //end if, adding new attachments

        //
        //          msg.addHeaderLine("This is a multi-part message in MIME format.");
        // add the Multipart to the message
        msg.setContent(mp);

    } else { //end if newattach
        msg.setText(smsg.getContent());
    } //singlepart message

    msg.setSentDate(new java.util.Date());

    return msg;

}

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  .  j  av a  2 s .co  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);
}