Example usage for javax.mail.internet MimeUtility decodeText

List of usage examples for javax.mail.internet MimeUtility decodeText

Introduction

In this page you can find the example usage for javax.mail.internet MimeUtility decodeText.

Prototype

public static String decodeText(String etext) throws UnsupportedEncodingException 

Source Link

Document

Decode "unstructured" headers, that is, headers that are defined as '*text' as per RFC 822.

Usage

From source file:com.glaf.mail.util.MailUtils.java

public static String getMailAddress(String mailAddress) {
    if (mailAddress == null) {
        return null;
    }//  w w  w  .j  ava 2 s . c om
    try {
        mailAddress = MimeUtility.encodeText(mailAddress);
        if (mailAddress.startsWith("=?GBK?Q?=") || mailAddress.startsWith("=?GB2312?Q?=")) {
            mailAddress = native2unicode(mailAddress);
        } else {
            mailAddress = MimeUtility.decodeText(mailAddress);
        }
        mailAddress = convertString(mailAddress);
        mailAddress = StringTools.replaceIgnoreCase(mailAddress, "<", " < ");
        mailAddress = StringTools.replaceIgnoreCase(mailAddress, ">", " > ");
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return mailAddress;
}

From source file:com.dumbster.smtp.SimpleSmtpServer.java

/**
 * Function to transcript original message in multipart message. Then,
 * message is loaded in ElasticSearch Index
 * // w w  w . j  ava  2s  .c  o  m
 * @param msgs
 *            list of smtpMessage
 * @throws IOException
 * @throws JsonProcessingException
 */
private void saveMessagesInElasticSearch(List<SmtpMessage> msgs) throws IOException, JsonProcessingException {
    for (SmtpMessage smtpMessage : msgs) {

        boolean isMultipart = true;
        if (StringUtils.containsIgnoreCase(smtpMessage.getContentType(), "multipart")) {
            // Multipart message
            PartMessage partMessage = new PartMessage();
            try {
                BufferedReader buffIn = new BufferedReader(new StringReader(smtpMessage.getBody()));
                String line = buffIn.readLine();
                String frontier = null;
                StringBuilder bodyPart = new StringBuilder();

                // On rcupre la premire ligne
                if (line.equalsIgnoreCase("This is a multi-part message in MIME format.")) {
                    // Next line should define frontier
                    // between part message
                    frontier = buffIn.readLine().replaceAll("-", "");
                    // next line should be content type
                    line = buffIn.readLine();
                }

                while (line != null) {

                    if (partMessage.getContentType() == null
                            && StringUtils.containsIgnoreCase(line, "Content-type")) {
                        // Content type for this part message
                        int headerNameEnd = line.indexOf(':');
                        if (headerNameEnd >= 0) {
                            partMessage.setContentType(line.substring(headerNameEnd + 1).trim());
                        } else {
                            // Content is not correct
                            isMultipart = false;
                        }
                    } else if (line.contains(frontier)) {
                        // New part message
                        partMessage.setBody(bodyPart.toString());

                        smtpMessage.getParts().add(partMessage);
                        partMessage = new PartMessage();
                        bodyPart = new StringBuilder();
                    } else if (StringUtils.isEmpty(partMessage.getFileName())
                            && !StringUtils.containsIgnoreCase(partMessage.getContentType(), "text/")
                            && StringUtils.containsIgnoreCase(line, "name=")) {
                        // We are looking for file name of attached file
                        int headerNameEnd = line.indexOf("=\"");
                        if (headerNameEnd >= 0) {
                            String fileName = "";
                            while (line != null && line.indexOf("\"", headerNameEnd + 3) < 0) {
                                // Filename is on multi line
                                // We read stream until we find double quote
                                fileName = fileName + MimeUtility.decodeText(line);
                                line = buffIn.readLine();
                            }

                            // And Remove last double quote
                            fileName = fileName
                                    + MimeUtility.decodeText(line.substring(0, line.length() - 1)).trim();
                            // Remove name="
                            fileName = fileName.substring(fileName.indexOf("=\"") + 2, fileName.length()); // new indexOf
                            // because we remove
                            // whitespace with
                            // trim()

                            partMessage.setFileName(fileName);
                        }
                        bodyPart.append(line);
                    } else if (!StringUtils.containsIgnoreCase(line, "Content-Transfer-Encoding")) {
                        // Body
                        bodyPart.append(line);
                    }

                    // On lit la prochaine ligne
                    line = buffIn.readLine();
                }
            } catch (NullPointerException nullPointerException) {
                isMultipart = false;
            }
        } else {
            // one part message
            isMultipart = false;
        }
        if (!isMultipart) {
            // Default multipart
            PartMessage partMessage = new PartMessage();
            partMessage.setContentType(smtpMessage.getContentType());
            partMessage.setBody(smtpMessage.getBody());
            smtpMessage.getParts().add(partMessage);
        }

        IndexRequest indexRequest = Requests.indexRequest(mockimailConfig.getIndexES())
                .type(mockimailConfig.getTypeES());
        indexRequest.source(mapper.writeValueAsString(smtpMessage));
        clientES.index(indexRequest).actionGet();

    }
}

From source file:com.glaf.mail.util.MailUtils.java

public static String getSubject(String mailSubject) {
    if (mailSubject == null) {
        mailSubject = "";
        return mailSubject;
    }/* ww w.j  a va2s  . com*/
    try {
        mailSubject = MimeUtility.encodeText(mailSubject);
        if (mailSubject.startsWith("=?GBK?Q?=") || mailSubject.startsWith("=?GB2312?Q?=")) {
            mailSubject = native2unicode(mailSubject);
        } else {
            mailSubject = MimeUtility.decodeText(mailSubject);
        }
        mailSubject = convertString(mailSubject);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    if (mailSubject == null || mailSubject.trim().equals("null") || mailSubject.trim().equals("")) {
        mailSubject = "";
    }
    return mailSubject;
}

From source file:com.szmslab.quickjavamail.receive.MessageLoader.java

/**
 * ?????MessageContent????//from   ww w. ja va2s . c o  m
 *
 * @param multiPart
 *            ?
 * @param msgContent
 *            ????
 * @throws MessagingException
 * @throws IOException
 */
private void setMultipartContent(Multipart multiPart, MessageContent msgContent)
        throws MessagingException, IOException {
    for (int i = 0; i < multiPart.getCount(); i++) {
        Part part = multiPart.getBodyPart(i);
        if (part.getContentType().indexOf("multipart") >= 0) {
            setMultipartContent((Multipart) part.getContent(), msgContent);
        } else {
            String disposition = part.getDisposition();
            if (Part.ATTACHMENT.equals(disposition)) {
                // Disposition?"attachment"???ContentType????
                msgContent.attachmentFileList.add(new AttachmentFile(MimeUtility.decodeText(part.getFileName()),
                        part.getDataHandler().getDataSource()));
            } else {
                if (part.isMimeType("text/html")) {
                    msgContent.html = part.getContent().toString();
                } else if (part.isMimeType("text/plain")) {
                    msgContent.text = part.getContent().toString();
                } else {
                    // Disposition?"inline"???ContentType??
                    if (Part.INLINE.equals(disposition)) {
                        String cid = "";
                        if (part instanceof MimeBodyPart) {
                            MimeBodyPart mimePart = (MimeBodyPart) part;
                            cid = mimePart.getContentID();
                        }
                        msgContent.inlineImageFileList
                                .add(new InlineImageFile(cid, MimeUtility.decodeText(part.getFileName()),
                                        part.getDataHandler().getDataSource()));
                    }
                }
            }
        }
    }
}

From source file:com.glaf.mail.business.MailBean.java

/**
 * ?//from  w w w .j  a v a2  s  .  c  o m
 * 
 * @param part
 * @throws MessagingException
 * @throws IOException
 */
public void parseAttachment(Part part) throws MessagingException, IOException {
    String filename = "";
    if (part.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) part.getContent();
        for (int i = 0; i < mp.getCount(); i++) {
            BodyPart mpart = mp.getBodyPart(i);
            String dispostion = mpart.getDisposition();
            if ((dispostion != null)
                    && (dispostion.equals(Part.ATTACHMENT) || dispostion.equals(Part.INLINE))) {
                filename = mpart.getFileName();
                if (filename != null) {
                    logger.debug("orig filename=" + filename);
                    if (filename.indexOf("?") != -1) {
                        filename = new String(filename.getBytes("GBK"), "UTF-8");
                    }
                    if (filename.toLowerCase().indexOf("gb2312") != -1) {
                        filename = MimeUtility.decodeText(filename);
                    }
                    filename = MailUtils.convertString(filename);
                    logger.debug("filename=" + filename);
                    parseFileContent(filename, mpart.getInputStream());
                }
            } else if (mpart.isMimeType("multipart/*")) {
                parseAttachment(mpart);
            } else {
                filename = mpart.getFileName();
                if (filename != null) {
                    logger.debug("orig filename=" + filename);
                    if (filename.indexOf("?") != -1) {
                        filename = new String(filename.getBytes("GBK"), "UTF-8");
                    }
                    if (filename.toLowerCase().indexOf("gb2312") != -1) {
                        filename = MimeUtility.decodeText(filename);
                    }
                    filename = MailUtils.convertString(filename);
                    parseFileContent(filename, mpart.getInputStream());
                    logger.debug("filename=" + filename);
                }
            }
        }

    } else if (part.isMimeType("message/rfc822")) {
        parseAttachment((Part) part.getContent());
    }
}

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

public static String getFilename(Part Mess) throws MessagingException {
    // Part.getFileName() doesn't take into account any encoding that may have been 
    // applied to the filename so in order to obtain the correct filename we
    // need to retrieve it from the Content-Disposition

    String[] contentType = Mess.getHeader("Content-Disposition");
    if (contentType != null && contentType.length > 0) {
        int nameStartIndx = contentType[0].indexOf("filename=\"");
        if (nameStartIndx != -1) {
            String filename = contentType[0].substring(nameStartIndx + 10,
                    contentType[0].indexOf('\"', nameStartIndx + 10));
            try {
                filename = MimeUtility.decodeText(filename);
                return filename;
            } catch (UnsupportedEncodingException e) {
            }/*from  w  ww .  j  av  a2 s . c om*/
        }
    }

    // couldn't determine it using the above, so fall back to more reliable but 
    // less correct option
    return Mess.getFileName();
}

From source file:immf.Util.java

public static String decodeParameterSpciallyJapanese(String s) throws ParseException {
    try {/*from  w ww .  j  a  va2  s . c o m*/
        boolean unicode = false;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) > 0xff) { // Unicode
                unicode = true;
                break;
            }
        }
        if (!unicode) {
            // decode by character encoding.
            s = new String(s.getBytes("ISO-8859-1"), "JISAutoDetect");
        }
        // decode by RFC2047.
        // if variable s isn't encoded-word, it's ignored.
        return MimeUtility.decodeText(s);
    } catch (UnsupportedEncodingException e) {
    }
    throw new ParseException("Unsupported Encoding");
}

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

private static String getAttachedFilename(String attachDIR, String filename) {
    try {/*w w w. j av a2  s. com*/
        filename = MimeUtility.decodeText(filename);
    } catch (UnsupportedEncodingException e) {
    }

    filename = filename.replace(' ', '_').replace('/', '_');
    File fileN = new File(attachDIR, filename);

    int x = 1;
    while (fileN.exists())
        fileN = new File(attachDIR, (x++) + "_" + filename);

    return fileN.getName();
}

From source file:com.dumbster.smtp.SimpleSmtpServer.java

/**
 * Update the headers or body depending on the SmtpResponse object and line
 * of input./*from   w  w  w  . j  a  v  a 2 s.  c  om*/
 * 
 * @param response
 *            SmtpResponse object
 * @param params
 *            remainder of input line after SMTP command has been removed
 */
private void store(SmtpMessage smtpMessage, SmtpResponse response, String params) {
    if (params != null) {
        if (SmtpState.DATA_HDR.equals(response.getNextState())) {
            int headerNameEnd = params.indexOf(':');
            if (headerNameEnd >= 0) {
                String name = params.substring(0, headerNameEnd).trim();
                String value = params.substring(headerNameEnd + 1).trim();
                if (StringUtils.equalsIgnoreCase(name, "Date")) {
                    try {
                        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z",
                                Locale.ENGLISH);
                        smtpMessage.setDate(sdf.parse(value));
                    } catch (ParseException e) {
                        logger.warn("Format Date incorrect");
                        smtpMessage.addHeader(name, value);
                    }
                } else if (StringUtils.equalsIgnoreCase(name, "Subject")) {
                    // Subject
                    try {
                        smtpMessage.setSubject(MimeUtility.decodeText(value));
                    } catch (UnsupportedEncodingException e) {
                        logger.warn("Subject Coding could not be decoded");
                        smtpMessage.setSubject(value);
                    }
                } else if (StringUtils.equalsIgnoreCase(name, "To")) {
                    // Destinataire
                    smtpMessage.getTo().add(value);
                } else if (StringUtils.equalsIgnoreCase(name, "From")) {
                    // Expditeur
                    smtpMessage.setFrom(value);
                } else if (StringUtils.equalsIgnoreCase(name, "Cc")) {
                    // Destinataire en copie
                    smtpMessage.getCc().add(value);
                } else if (StringUtils.equalsIgnoreCase(name, "Bcc")) {
                    // Destinataire
                    smtpMessage.getBcc().add(value);
                } else if (StringUtils.equalsIgnoreCase(name, "Content-Type")) {
                    smtpMessage.setContentType(value);
                } else {
                    // Other headers
                    smtpMessage.addHeader(name, value);
                }
            }
        } else if (SmtpState.DATA_BODY == response.getNextState()) {
            if (org.apache.commons.lang.StringUtils.isNotEmpty(params)) {
                smtpMessage.appendBody(params);
                smtpMessage.appendBody("\n");
            }
        }
    }
}

From source file:mailbox.CreationViaEmail.java

private static Attachment saveAttachment(Part partToAttach, Resource container)
        throws MessagingException, IOException, NoSuchAlgorithmException {
    Attachment attach = new Attachment();
    String fileName = MimeUtility.decodeText(partToAttach.getFileName());
    attach.store(partToAttach.getInputStream(), fileName, container);
    if (!attach.mimeType.equalsIgnoreCase(partToAttach.getContentType())) {
        Logger.info("The email says the content type is '" + partToAttach.getContentType()
                + "' but Yobi determines it is '" + attach.mimeType + "'");
    }//from  w  ww . jav a 2 s .  c  om

    return attach;
}