Example usage for javax.mail Part getFileName

List of usage examples for javax.mail Part getFileName

Introduction

In this page you can find the example usage for javax.mail Part getFileName.

Prototype

public String getFileName() throws MessagingException;

Source Link

Document

Get the filename associated with this part, if possible.

Usage

From source file:mitm.common.mail.MimeUtils.java

/**
 * Returns the filename of the part. If getting the filename results in a
 * MessagingException the exception is handled and null is returned.
 * /*w  ww  . j  a  v  a 2s .  co  m*/
 * The reason this function is used is that sometimes mail contains an invalid
 * Content-Disposition header. This results in an exception being thrown when
 * accessing the filename.
 */
public static String getFilenameQuietly(Part part) {
    String filename = null;

    try {
        filename = part.getFileName();
    } catch (MessagingException e) {
        logger.debug("Error while getting the filename.", e);
    }

    return filename;
}

From source file:org.silverpeas.util.mail.EMLExtractor.java

private static String getFileName(Part part) throws MessagingException {
    String fileName = part.getFileName();
    if (!StringUtil.isDefined(fileName)) {
        try {//from   w w w . jav  a 2s.  c o  m
            ContentType type = new ContentType(part.getContentType());
            fileName = type.getParameter("name");
        } catch (ParseException e) {
            SilverTrace.error("util", EMLExtractor.class.getSimpleName() + ".getFileName", "root.EX_NO_MESSAGE",
                    e);
        }
    }
    if (StringUtil.isDefined(fileName) && fileName.startsWith("=?") && fileName.endsWith("?=")) {
        try {
            fileName = MimeUtility.decodeText(part.getFileName());
        } catch (UnsupportedEncodingException e) {
            SilverTrace.error("util", EMLExtractor.class.getSimpleName() + ".getFileName", "root.EX_NO_MESSAGE",
                    e);
        }
    }
    return fileName;
}

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

protected static String getFilename(Part p, String defaultFileName) throws MessagingException {
    String originalFilename = p.getFileName();
    if (originalFilename == null || originalFilename.trim().length() == 0) {
        String filename = defaultFileName;
        // using default filename => add extension for this type
        if (p.isMimeType("text/plain")) {
            filename += ".txt";
        } else if (p.isMimeType("text/html")) {
            filename += ".html";
        }//from w  w  w  .j  av a 2 s. c om
        return filename;
    } else {
        try {
            return MimeUtility.decodeText(originalFilename.trim());
        } catch (UnsupportedEncodingException e) {
            return originalFilename.trim();
        }
    }
}

From source file:com.canoo.webtest.plugins.emailtest.EmailMessageStructureFilter.java

private static String processMessagePart(final Part part) throws MessagingException {
    final String disp = part.getDisposition();
    final String contentType = part.getContentType();
    if (Part.ATTACHMENT.equals(disp)) {
        return "    <part type=\"attachment\" filename=\"" + part.getFileName() + "\" contentType=\""
                + extractBaseContentType(contentType) + "\"/>" + LS;
    }/*from   w  ww  . j  a  v  a 2  s .  co m*/
    return "    <part type=\"inline\" contentType=\"" + extractBaseContentType(contentType) + "\"/>" + LS;
}

From source file:org.apache.hupa.server.utils.MessageUtils.java

/**
 * Loop over MuliPart and write the content to the Outputstream if a
 * attachment with the given name was found.
 *
 * @param logger/*from   w ww  .j a v  a 2s. com*/
 *            The logger to use
 * @param content
 *            Content which should checked for attachments
 * @param attachmentName
 *            The attachmentname or the unique id for the searched attachment
 * @throws MessagingException
 * @throws IOException
 */
public static Part handleMultiPart(Log logger, Object content, String attachmentName)
        throws MessagingException, IOException {
    if (content instanceof Multipart) {
        Multipart part = (Multipart) content;
        for (int i = 0; i < part.getCount(); i++) {
            Part bodyPart = part.getBodyPart(i);
            String fileName = bodyPart.getFileName();
            String[] contentId = bodyPart.getHeader("Content-ID");
            if (bodyPart.isMimeType("multipart/*")) {
                Part p = handleMultiPart(logger, bodyPart.getContent(), attachmentName);
                if (p != null)
                    return p;
            } else {
                if (contentId != null) {
                    for (String id : contentId) {
                        id = id.replaceAll("^.*<(.+)>.*$", "$1");
                        System.out.println(attachmentName + " " + id);
                        if (attachmentName.equals(id))
                            return bodyPart;
                    }
                }
                if (fileName != null) {
                    if (cleanName(attachmentName).equalsIgnoreCase(cleanName(MimeUtility.decodeText(fileName))))
                        return bodyPart;
                }
            }
        }
    } else {
        logger.error("Unknown content: " + content.getClass().getName());
    }
    return null;
}

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

/**
 * "javax.mail.internet.MimeBodyPart" is decoding the file name (with special characters) if it has the
 * "mail.mime.decodefilename" sysstem property set but the "com.sun.mail.imap.IMAPBodyPart" subclass of MimeBodyPart
 * is overriding getFileName() and never deal with encoded file names. the filename is decoded with the utility
 * function: MimeUtility.decodeText(filename); so we force here a filename decode. MimeUtility.decodeText is doing
 * nothing if the text is not encoded/* w w  w. j  a  va 2 s.  c  o m*/
 */
private static String getFileName(Part mailPart) throws MessagingException {
    String sysPropertyVal = System.getProperty("mail.mime.decodefilename");
    boolean decodeFileName = sysPropertyVal != null && !sysPropertyVal.equalsIgnoreCase("false");

    String encodedFilename = mailPart.getFileName();

    if (!decodeFileName || encodedFilename == null) {
        return encodedFilename;
    }

    try {
        return MimeUtility.decodeText(encodedFilename);
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Can't decode attachment filename.", ex);
    }
}

From source file:com.email.ReceiveEmail.java

/**
 * Save the attachments from the email/*from   ww w  .j  ava  2  s  .c om*/
 *
 * @param p Part
 * @param m Message
 * @param eml EmailMessageModel
 */
private static void saveAttachments(Part p, Message m, EmailMessageModel eml) {
    try {
        String filename = p.getFileName();
        if (filename != null && !filename.endsWith("vcf")) {
            try {
                saveFile(p, filename, eml);
            } catch (ClassCastException ex) {
                System.err.println("CRASH");
            }
        } else if (p.isMimeType("IMAGE/*")) {
            saveFile(p, filename, eml);
        }
        if (p.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) p.getContent();
            int pageCount = mp.getCount();
            for (int i = 0; i < pageCount; i++) {
                saveAttachments(mp.getBodyPart(i), m, eml);
            }
        } else if (p.isMimeType("message/rfc822")) {
            saveAttachments((Part) p.getContent(), m, eml);
        }
    } catch (IOException | MessagingException ex) {
        ExceptionHandler.Handle(ex);
    }
}

From source file:org.simplejavamail.internal.util.MimeMessageParser.java

/**
 * Determines the name of the data source if it is not already set.
 *
 * @param part       the mail part//w ww  .  java 2 s.c om
 * @param dataSource the data source
 * @return the name of the data source or {@code null} if no name can be determined
 * @throws MessagingException           accessing the part failed
 * @throws UnsupportedEncodingException decoding the text failed
 */
private static String getDataSourceName(final Part part, final DataSource dataSource)
        throws MessagingException, UnsupportedEncodingException {
    String result = dataSource.getName();

    if (result == null || result.length() == 0) {
        result = part.getFileName();
    }

    if (result != null && result.length() > 0) {
        result = MimeUtility.decodeText(result);
    } else {
        result = null;
    }

    return result;
}

From source file:dtw.webmail.model.JwmaMessagePartImpl.java

/**
 * Creates a <tt>JwmaMessagePartImpl</tt> instance from a given
 * <tt>javax.mail.Part</tt> instance.
 *
 * @param part a <tt>javax.mail.Part</tt> instance.
 * @param number the number of the part as <tt>int</tt>.
 *
 * @return the newly created instance./*w  ww .  j  a  va 2s.  com*/
 * @throws JwmaException if it fails to create the new instance.
 */
public static JwmaMessagePartImpl createJwmaMessagePartImpl(Part part, int number) throws JwmaException {
    JwmaMessagePartImpl partinfo = new JwmaMessagePartImpl(part, number);

    //content type
    try {
        partinfo.setContentType(part.getContentType());

        //size
        int size = part.getSize();
        //JwmaKernel.getReference().debugLog().write("Part size="+size);
        String fileName = part.getFileName();
        //correct size of encoded parts
        String[] encoding = part.getHeader("Content-Transfer-Encoding");
        if (fileName != null && encoding != null && encoding.length > 0
                && (encoding[0].equalsIgnoreCase("base64") || encoding[0].equalsIgnoreCase("uuencode"))) {
            if ((fileName.startsWith("=?GB2312?B?") && fileName.endsWith("?="))) {
                byte[] decoded = Base64.decodeBase64(fileName.substring(11, fileName.indexOf("?=")).getBytes());
                fileName = new String(decoded, "GB2312");
                /*fileName = CipherUtils.decrypt(fileName);
                System.out.println("fileName----"+fileName);*/
                //fileName = getFromBASE64(fileName.substring(11,fileName.indexOf("?=")));  
            } else if ((fileName.startsWith("=?UTF-8?") || fileName.startsWith("=?UTF8?"))
                    && fileName.endsWith("?=")) {
                fileName = MimeUtility.decodeText(fileName);
            }
            //an encoded file is about 35% smaller in reality,
            //so correct the size
            size = (int) (size * 0.65);
        }

        partinfo.setSize(size);
        //description
        partinfo.setDescription(part.getDescription());

        //filename
        partinfo.setName(fileName);

        //textcontent
        if (partinfo.isMimeType("text/*")) {
            Object content = part.getContent();
            if (content instanceof String) {
                partinfo.setTextContent((String) content);
            } else if (content instanceof InputStream) {
                InputStream in = (InputStream) content;
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                byte[] buffer = new byte[8192];
                int amount = 0;
                while ((amount = in.read(buffer)) >= 0) {
                    bout.write(buffer, 0, amount);
                }
                partinfo.setTextContent(new String(bout.toString()));
            }
        }
    } catch (Exception mex) {
        throw new JwmaException("jwma.messagepart.failedcreation", true).setException(mex);
    }
    return partinfo;
}

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  ww w .ja  va2 s  . co m

    return attach;
}