⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 javamailgateway.java

📁 jive 2.1.1 的源码
💻 JAVA
📖 第 1 页 / 共 5 页
字号:

    /**
     * Returns the parent ID's of a message as a String [] or null if there are
     * no parents.
     *
     * @param message the JavaMail message.
     * @param header the header to use to lookup the parent message id.
     * @return String the parent message id (null if not found).
     * @throws MessagingException if something goes wrong.
     */
    protected String[] getParentMessageID(Message message, String header)
            throws MessagingException
    {
        String temp [] = message.getHeader(header);
        // The most likely case is that there aren't any parents
        if (temp == null || temp[0] == null || temp[0].equals("")) {
           return null;
        }
        // the last message id is the actual parent to this message, the first
        // is the top parent to this thread
        StringTokenizer st            = new StringTokenizer(temp[0], " ");
        java.util.LinkedList pParents = new java.util.LinkedList();

        // we have more than 1 parent
        // verify format and add to end of List
        if (st.hasMoreTokens()) {
            String t = "";
            while (st.hasMoreTokens()) {
                t = st.nextToken();
                if (t.charAt(0) == '<' && t.charAt(t.length()-1) == '>') {
                    pParents.addFirst(t);
                }
            }
        }
        // single parent, verify format
        else {
            if (temp[0].charAt(0) == '<' &&
                    temp[0].charAt(temp[0].length()-1) == '>') {
                pParents.addFirst(temp[0]);
            }
        }

        if (!pParents.isEmpty()) {
            return (String[]) pParents.toArray(new String[pParents.size()]);
        }
        else {
            return null;
        }
    }

    /**
     * Retrieve the from email name
     * don't let javaMail parse the address since it sometimes
     * won't handle odd addresses like the following one I found
     * "Mike [remove (SPAM_BLOCKER) from my email address to reply]"
     *    <aen(SPAM_BLOCKER)eas@gw(SPAM_BLOCKER)is.com>
     *
     * In most cases we default to returning the whole from string if we can't
     * determine the name because of a poorly formatted header
     *
     * @param message the JavaMail message
     * @return String the from name
     * @throws MessagingException if JavaMail throws an exception
     */
    protected String getFromName(Message message)
            throws MessagingException {

        String[] fromAddresses = message.getHeader("From");
        String fromAddress     = "";
        String fromName        = "";

        if (fromAddresses != null) {
            fromAddress = fromAddresses[0];

            // In format -- First Last <person@place.com>
            if (fromAddress.indexOf("<") != -1) {
                int nameEnd = fromAddress.indexOf("<");
                if (nameEnd > 0) {
                    fromName = fromAddress.substring(0, nameEnd).trim();
                    fromName = StringUtils.replace(fromName, "\"", " ").trim();
                }
                else {
                    fromName = fromAddress;
                }
            }
            // In format -- person@place.com (First Last)
            else if (fromAddress.indexOf("(") != -1) {
                int nameStart   = fromAddress.indexOf("(");
                fromName = fromAddress.substring(nameStart+1, fromAddress.length()-1);

                // broken, try name (
                if (fromName.length() < 1 && nameStart != 0) {
                    fromName = fromAddress.substring(0,nameStart);

                    if (fromName.length() < 1) {
                        fromName = fromAddress;
                    }
                }
            }
            // In format -- person@place.com
            else {
                fromName = fromAddress;
            }

            try {
                return getRFC2047DecodedString(fromName);
            }
            catch (Exception e) {
                return fromName;
            }
        }
        else {
            return "";
        }
    }


    /**
     * Retrieve the from email address
     * don't let javaMail parse the address since it sometimes
     * won't handle odd addresses
     *
     * In most cases we default to returning the whole from string if we can't
     * determine the email address because of a poorly formatted header
     *
     * @param message the JavaMail message
     * @return String the from email address
     * @throws MessagingException if JavaMail throws an exception
     */
    protected String getFromEmail(Message message)
            throws MessagingException {

        String[] fromAddresses = message.getHeader("From");
        int index              = 0;
        String fromAddress     = "";

        if (fromAddresses != null && fromAddresses.length > 0) {
            fromAddress = fromAddresses[0].toString();

            // In format -- First Last <person@place.com>
            // first we check for the existance of quotes, if found
            // we search after them for the string
            if (fromAddress.indexOf("\"") != -1) {
                index = fromAddress.indexOf("\"");
            }

            if (fromAddress.indexOf("<", index) != -1) {
                int nameEnd = fromAddress.indexOf("<");
                int emailEnd = fromAddress.indexOf(">", nameEnd);
                if (emailEnd > 0) {
                    return fromAddress.substring(nameEnd + 1, emailEnd);
                }
                else {
                    return fromAddress;
                }
            }
            // In format -- person@place.com (First Last)
            else if (fromAddress.indexOf("(") != -1) {
                int nameStart = fromAddress.indexOf("(");
                return fromAddress.substring(0, (nameStart != 0) ? nameStart-1 : nameStart).trim();
            }
            // In format -- person@place.com
            else {
                return fromAddress;
            }
        }
        else {
            throw new MessagingException("No From address found!");
        }
    }


    /**
     * Retrieve the textual body of the message.
     *
     * @param message  the JavaMail message
     * @return String  the body of the message
     * @throws MessagingException if JavaMail throws an exception
     * @throws IOException if JavaMail throws an exception handling mime content
     */
    protected String getBody(Message message)
            throws MessagingException, IOException {

        // plain text message
        // search message content for uuencoded attachments, remove them
        // we should handle any octal character instead of just 666 ...
        // however I haven't encountered any other octet yet.
        if (message.isMimeType("text/plain") || message.isMimeType("text")) {
            BufferedReader reader = getTextReader((Part) message);
            String line           = "";
            boolean ignore        = false;
            StringBuffer sb       = new StringBuffer();

            try {
                while ((line = reader.readLine()) != null) {
                    if (line.indexOf("begin 666 ") == 0) {
                        sb.append("[").append(line.substring(9)).append("]\n");
                        ignore = true;
                    }
                    else if (ignore && line.indexOf("end") == 0) {
                        ignore = false;
                    }
                    else if (!ignore) {
                        sb.append(line).append("\n");
                    }
                }
            }
            finally {
                try { reader.close(); }
                catch (Exception e) { /* ignore */ }
            }

            return sb.toString();
        }

        // multipart message
        // save text attachments to the body, other attachments
        // get ignored here
        else if (message.isMimeType("multipart/*")) {
            try {
                return getTextParts((Multipart) message.getContent());
            }
            catch (IllegalArgumentException iae) {
                throw new MessagingException("Character set not recognized", iae);
            }
        }
        // not text, not multipart, likely html
        else {
            return "";
        }
    }

    /**
     * Get a reader object for a Part with the character set properly chosen.
     * Note that the reader object returned should be closed after use.
     *
     * @param part - a javax.mail.part object
     * @return a BufferedReader object
     */
    protected BufferedReader getTextReader(Part part) throws MessagingException {
        try {
            InputStream is = part.getInputStream();
            InputStreamReader reader = null;
            String charset = getTextEncoding(part);

            try {
                reader = new InputStreamReader(is, charset);
            }
            catch (UnsupportedEncodingException ex) {
                reader = null;
            }
            catch (IllegalArgumentException ex) {
                reader = null;
            }

            if (reader == null) {
                charset = MimeUtility.javaCharset("ASCII");
                reader = new InputStreamReader(is, charset);
            }

            BufferedReader bufferedReader = new BufferedReader(reader);
            return bufferedReader;
        }
        catch(IOException ioe) {
            throw new MessagingException(ioe.toString());
        }
    }

    /**
     * Utility method to retrieve the encoding from a part.
     *
     * @param part - a javax.mail.part object
     * @return the encoding, defaulting to ASCII
     */
    protected String getTextEncoding(Part part) {
        String charset = "";

        try {
            // get the character set from the content type
            ContentType xct = new ContentType(part.getContentType().toLowerCase());
            charset = xct.getParameter("charset");

            if (charset != null) {
                charset = MimeUtility.javaCharset(charset);
            }
            else {
                // assume ASCII character encoding
                charset = MimeUtility.javaCharset("ASCII");
            }
        }
        catch (MessagingException e) { /* ignore */ }

        return charset;
    }

    /**
     * Utility method to retrieve text parts of a multipart message
     * and return them
     *
     * @param mp a Multipart object to go through
     * @return String
     * @throws MessagingException if something goes wrong parsing the message
     * @throws IOException if JavaMail throws an exception handling mime content
     */
    private String getTextParts(Multipart mp)
        throws MessagingException, IOException {

        StringBuffer body = new StringBuffer();
        int cnt = mp.getCount();

        for (int j = 0; j < cnt; j++) {
            Part part       = mp.getBodyPart(j);
            String sct      = part.getContentType();
            ContentType ct  = null;

            // no content type?
            if (sct == null) {
                continue;
            }

            ct = new ContentType(sct);

            if (ct.match("text/plain") || ct.match("text")) {
                BufferedReader reader = getTextReader((Part) part);
                String line           = "";

                try {
                    while ((line = reader.readLine()) != null) {
                        body.append(line).append("\n");
                    }
                }
                catch (IOException e) { /* ignore */ }
                finally {
                    try { reader.close(); }
                    catch (Exception e) { /* ignore */ }
                }
            }
            else if (ct.match("multipart/*")) {
                Object o = part.getContent();

                if (o instanceof MimeMultipart) {

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -