Example usage for javax.mail Part INLINE

List of usage examples for javax.mail Part INLINE

Introduction

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

Prototype

String INLINE

To view the source code for javax.mail Part INLINE.

Click Source Link

Document

This part should be presented inline.

Usage

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./*w ww .  ja va  2  s .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.szmslab.quickjavamail.receive.MessageLoader.java

/**
 * ?????MessageContent????//from   w  w w . jav  a2 s .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:org.silverpeas.components.mailinglist.service.job.MailProcessor.java

/**
 * Analyze the part to check if it is an attachment, a base64 encoded file or some text.
 * @param part the part to be analyzed.//from w  w  w.  j  av a2 s  .  c  o  m
 * @return true if it is some text - false otherwise.
 * @throws MessagingException
 */
protected boolean isTextPart(Part part) throws MessagingException {
    String disposition = part.getDisposition();
    if (!Part.ATTACHMENT.equals(disposition) && !Part.INLINE.equals(disposition)) {
        try {
            ContentType type = new ContentType(part.getContentType());
            return "text".equalsIgnoreCase(type.getPrimaryType());
        } catch (ParseException e) {
            logger.error(e.getMessage(), e);
        }
    } else if (Part.INLINE.equals(disposition)) {
        try {
            ContentType type = new ContentType(part.getContentType());
            return "text".equalsIgnoreCase(type.getPrimaryType()) && getFileName(part) == null;
        } catch (ParseException e) {
            logger.error(e.getMessage(), e);
        }
    }
    return false;
}

From source file:com.silverpeas.mailinglist.service.job.MailProcessor.java

/**
 * Analyze the part to check if it is an attachment, a base64 encoded file or some text.
 *
 * @param part the part to be analyzed.//ww  w.  j  ava 2 s.  c  om
 * @return true if it is some text - false otherwise.
 * @throws MessagingException
 */
protected boolean isTextPart(Part part) throws MessagingException {
    String disposition = part.getDisposition();
    if (!Part.ATTACHMENT.equals(disposition) && !Part.INLINE.equals(disposition)) {
        try {
            ContentType type = new ContentType(part.getContentType());
            return "text".equalsIgnoreCase(type.getPrimaryType());
        } catch (ParseException e) {
            e.printStackTrace();
        }
    } else if (Part.INLINE.equals(disposition)) {
        try {
            ContentType type = new ContentType(part.getContentType());
            return "text".equalsIgnoreCase(type.getPrimaryType()) && getFileName(part) == null;
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    return false;
}

From source file:eu.openanalytics.rsb.component.EmailDepositHandler.java

private void addEmailAttachmentsToJob(final DepositEmailConfiguration depositEmailConfiguration,
        final MimeMessage mimeMessage, final MultiFilesJob job)
        throws MessagingException, IOException, FileNotFoundException {

    final String jobConfigurationFileName = depositEmailConfiguration.getJobConfigurationFileName();
    if (StringUtils.isNotBlank(jobConfigurationFileName)) {
        final File jobConfigurationFile = getJobConfigurationFile(
                depositEmailConfiguration.getApplicationName(), jobConfigurationFileName);
        job.addFile(Constants.MULTIPLE_FILES_JOB_CONFIGURATION, new FileInputStream(jobConfigurationFile));
    }/*w w  w  . j  av a 2  s  .co m*/

    final Object content = mimeMessage.getContent();
    Validate.isTrue(content instanceof Multipart, "only multipart emails can be processed");

    final Multipart multipart = (Multipart) content;
    for (int i = 0, n = multipart.getCount(); i < n; i++) {
        final Part part = multipart.getBodyPart(i);

        final String disposition = part.getDisposition();

        if ((disposition != null)
                && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) {
            final String name = part.getFileName();
            final String contentType = StringUtils.substringBefore(part.getContentType(), ";");
            MultiFilesJob.addDataToJob(contentType, name, part.getInputStream(), job);
        }
    }
}

From source file:immf.SendMailBridge.java

private void parseMultipart(SenderMail sendMail, Multipart mp, String subtype, String parentSubtype)
        throws IOException {
    String contentType = mp.getContentType();
    log.info("Multipart ContentType:" + contentType);

    try {/*from w  ww . ja v  a2  s .  co  m*/
        int count = mp.getCount();
        log.info("count " + count);

        boolean hasInlinePart = false;
        if (subtype.equalsIgnoreCase("mixed")) {
            for (int i = 0; i < count; i++) {
                String d = mp.getBodyPart(i).getDisposition();
                if (d != null && d.equalsIgnoreCase(Part.INLINE))
                    hasInlinePart = true;
            }
        }
        if (hasInlinePart) {
            log.info("parseBodypart(Content-Disposition:inline)");
            for (int i = 0; i < count; i++) {
                parseBodypartmixed(sendMail, mp.getBodyPart(i), subtype, parentSubtype);
            }
            if (sendMail.getHtmlContent() != null) {
                sendMail.addHtmlContent("</body>");
            }
            if (sendMail.getHtmlWorkingContent() != null) {
                sendMail.addHtmlWorkingContent("</body>");
            }
        } else {
            for (int i = 0; i < count; i++) {
                parseBodypart(sendMail, mp.getBodyPart(i), subtype, parentSubtype);
            }
        }
    } catch (Exception e) {
        log.error("parse multipart error.", e);
        //throw new IOException("MimeMultiPart error."+e.getMessage(),e);
    }
}

From source file:org.apache.camel.component.mail.MailBinding.java

protected void extractAttachmentsFromMultipart(Multipart mp, Map<String, DataHandler> map)
        throws javax.mail.MessagingException, IOException {

    for (int i = 0; i < mp.getCount(); i++) {
        Part part = mp.getBodyPart(i);// w  w  w .  j a  v a 2  s .c o  m
        LOG.trace("Part #" + i + ": " + part);

        if (part.isMimeType("multipart/*")) {
            LOG.trace("Part #" + i + ": is mimetype: multipart/*");
            extractAttachmentsFromMultipart((Multipart) part.getContent(), map);
        } else {
            String disposition = part.getDisposition();
            if (LOG.isTraceEnabled()) {
                LOG.trace("Part #" + i + ": Disposition: " + part.getDisposition());
                LOG.trace("Part #" + i + ": Description: " + part.getDescription());
                LOG.trace("Part #" + i + ": ContentType: " + part.getContentType());
                LOG.trace("Part #" + i + ": FileName: " + part.getFileName());
                LOG.trace("Part #" + i + ": Size: " + part.getSize());
                LOG.trace("Part #" + i + ": LineCount: " + part.getLineCount());
            }

            if (disposition != null && (disposition.equalsIgnoreCase(Part.ATTACHMENT)
                    || disposition.equalsIgnoreCase(Part.INLINE))) {
                // only add named attachments
                String fileName = part.getFileName();
                if (fileName != null) {
                    LOG.debug("Mail contains file attachment: " + fileName);
                    // Parts marked with a disposition of Part.ATTACHMENT are clearly attachments
                    CollectionHelper.appendValue(map, fileName, part.getDataHandler());
                }
            }
        }
    }
}

From source file:org.mxhero.engine.plugin.attachmentlink.alcommand.internal.domain.Message.java

private boolean isAttachInline(Part part) throws MessagingException {
    return part.getDisposition().equals(Part.INLINE);
}

From source file:de.kp.ames.web.function.access.imap.ImapConsumer.java

/**
 * @param part/*  w  w w .ja va2  s . c om*/
 * @param attach
 * @return
 * @throws Exception
 */
private FileUtil handlePart(Part part, boolean attach) throws Exception {

    FileUtil file = null;

    String disposition = part.getDisposition();
    if (disposition == null) {
        // no nothing

    } else if (disposition.equalsIgnoreCase(Part.ATTACHMENT) || disposition.equalsIgnoreCase(Part.INLINE)) {

        file = new FileUtil();

        String fileName = part.getFileName();
        String contentType = part.getContentType();

        /* 
         * The contentType parameter contains mimetype and filename in one
         */
        String mimeType = contentType.split(";")[0].trim();

        file.setFilename(fileName);
        file.setMimetype(mimeType);

        InputStream inputStream = (attach == true) ? part.getInputStream() : null;
        if (inputStream != null)
            file.setInputStream(inputStream, mimeType);

    }

    return file;

}

From source file:com.ikon.util.MailUtils.java

/**
 * Create a mail.//www  . jav a 2 s  .c  o m
 * 
 * @param fromAddress Origin address.
 * @param toAddress Destination addresses.
 * @param subject The mail subject.
 * @param text The mail body.
 * @throws MessagingException If there is any error.
 */
private static MimeMessage create(String fromAddress, Collection<String> toAddress, String subject, String text,
        Collection<String> docsPath, List<File> tmpAttachments) throws MessagingException,
        PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException {
    log.debug("create({}, {}, {}, {}, {})", new Object[] { fromAddress, toAddress, subject, text, docsPath });
    Session mailSession = getMailSession();
    MimeMessage msg = new MimeMessage(mailSession);

    if (fromAddress != null) {
        InternetAddress from = new InternetAddress(fromAddress);
        msg.setFrom(from);
    } else {
        msg.setFrom();
    }

    InternetAddress[] to = new InternetAddress[toAddress.size()];
    int idx = 0;

    for (Iterator<String> it = toAddress.iterator(); it.hasNext();) {
        to[idx++] = new InternetAddress(it.next());
    }

    // Build a multiparted mail with HTML and text content for better SPAM behaviour
    Multipart content = new MimeMultipart();

    // HTML Part
    MimeBodyPart htmlPart = new MimeBodyPart();
    StringBuilder htmlContent = new StringBuilder();
    htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n");
    htmlContent.append("<html>\n<head>\n");
    htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n");
    htmlContent.append("</head>\n<body>\n");
    htmlContent.append(text);
    htmlContent.append("\n</body>\n</html>");
    htmlPart.setContent(htmlContent.toString(), "text/html;charset=UTF-8");
    htmlPart.setHeader("Content-Type", "text/html;charset=UTF-8");
    htmlPart.setDisposition(Part.INLINE);
    content.addBodyPart(htmlPart);
    idx = 0;

    if (docsPath != null) {
        for (String docPath : docsPath) {
            InputStream is = null;
            FileOutputStream fos = null;
            String docName = PathUtils.getName(docPath);

            try {
                final Document doc = OKMDocument.getInstance().getProperties(null, docPath);
                is = OKMDocument.getInstance().getContent(null, docPath, false);
                final File tmpAttch = tmpAttachments.get(idx++);
                fos = new FileOutputStream(tmpAttch);
                IOUtils.copy(is, fos);
                fos.flush();

                // Document attachment part
                MimeBodyPart docPart = new MimeBodyPart();
                DataSource source = new FileDataSource(tmpAttch.getPath()) {
                    public String getContentType() {
                        return doc.getMimeType();
                    }
                };

                docPart.setDataHandler(new DataHandler(source));
                docPart.setFileName(MimeUtility.encodeText(docName));
                docPart.setDisposition(Part.ATTACHMENT);
                content.addBodyPart(docPart);
            } finally {
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(fos);
            }
        }
    }

    msg.setHeader("MIME-Version", "1.0");
    msg.setHeader("Content-Type", content.getContentType());
    msg.addHeader("Charset", "UTF-8");
    msg.setRecipients(Message.RecipientType.TO, to);
    msg.setSubject(subject, "UTF-8");
    msg.setSentDate(new Date());
    msg.setContent(content);
    msg.saveChanges();

    log.debug("create: {}", msg);
    return msg;
}