Example usage for javax.mail Part getDisposition

List of usage examples for javax.mail Part getDisposition

Introduction

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

Prototype

public String getDisposition() throws MessagingException;

Source Link

Document

Return the disposition of this part.

Usage

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  a  va 2s .com*/

    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:org.alfresco.module.org_alfresco_module_rm.action.impl.SplitEmailAction.java

/**
 * @see org.alfresco.repo.action.executer.ActionExecuterAbstractBase#executeImpl(org.alfresco.service.cmr.action.Action,
 *      org.alfresco.service.cmr.repository.NodeRef)
 *//*from w w  w.j a v a2  s.c  om*/
@Override
protected void executeImpl(Action action, NodeRef actionedUponNodeRef) {
    // get node type
    getNodeService().getType(actionedUponNodeRef);

    if (logger.isDebugEnabled()) {
        logger.debug("split email:" + actionedUponNodeRef);
    }

    if (getRecordService().isRecord(actionedUponNodeRef)) {
        if (!getRecordService().isDeclared(actionedUponNodeRef)) {
            ChildAssociationRef parent = getNodeService().getPrimaryParent(actionedUponNodeRef);

            /**
             * Check whether the email message has already been split - do nothing if it has already been split
             */
            List<AssociationRef> refs = getNodeService().getTargetAssocs(actionedUponNodeRef,
                    ImapModel.ASSOC_IMAP_ATTACHMENT);
            if (refs.size() > 0) {
                if (logger.isDebugEnabled()) {
                    logger.debug("mail message has already been split - do nothing");
                }
                return;
            }

            /**
             * Get the content and if its a mime message then create atachments for each part
             */
            try {
                ContentReader reader = getContentService().getReader(actionedUponNodeRef,
                        ContentModel.PROP_CONTENT);
                InputStream is = reader.getContentInputStream();
                MimeMessage mimeMessage = new MimeMessage(null, is);
                Object content = mimeMessage.getContent();
                if (content instanceof Multipart) {
                    Multipart multipart = (Multipart) content;

                    for (int i = 0, n = multipart.getCount(); i < n; i++) {
                        Part part = multipart.getBodyPart(i);
                        if ("attachment".equalsIgnoreCase(part.getDisposition())) {
                            createAttachment(actionedUponNodeRef, parent.getParentRef(), part);
                        }
                    }
                }
            } catch (Exception e) {
                throw new AlfrescoRuntimeException(I18NUtil.getMessage(MSG_NO_READ_MIME_MESSAGE, e.toString()),
                        e);
            }
        } else {
            throw new AlfrescoRuntimeException(
                    I18NUtil.getMessage(MSG_EMAIL_DECLARED, actionedUponNodeRef.toString()));
        }
    } else {
        throw new AlfrescoRuntimeException(
                I18NUtil.getMessage(MSG_EMAIL_NOT_RECORD, actionedUponNodeRef.toString()));
    }
}

From source file:org.alfresco.repo.imap.AttachmentsExtractor.java

public void extractAttachments(NodeRef messageRef, MimeMessage originalMessage)
        throws IOException, MessagingException {
    NodeRef attachmentsFolderRef = null;
    String attachmentsFolderName = null;
    boolean createFolder = false;
    switch (attachmentsExtractorMode) {
    case SAME:/*w  ww . j av  a  2 s. c o  m*/
        attachmentsFolderRef = nodeService.getPrimaryParent(messageRef).getParentRef();
        break;
    case COMMON:
        attachmentsFolderRef = this.attachmentsFolderRef;
        break;
    case SEPARATE:
    default:
        String messageName = (String) nodeService.getProperty(messageRef, ContentModel.PROP_NAME);
        attachmentsFolderName = messageName + "-attachments";
        createFolder = true;
        break;
    }
    if (!createFolder) {
        nodeService.createAssociation(messageRef, attachmentsFolderRef,
                ImapModel.ASSOC_IMAP_ATTACHMENTS_FOLDER);
    }

    Object content = originalMessage.getContent();
    if (content instanceof Multipart) {
        Multipart multipart = (Multipart) content;

        for (int i = 0, n = multipart.getCount(); i < n; i++) {
            Part part = multipart.getBodyPart(i);
            if ("attachment".equalsIgnoreCase(part.getDisposition())) {
                if (createFolder) {
                    attachmentsFolderRef = createAttachmentFolder(messageRef, attachmentsFolderName);
                    createFolder = false;
                }
                createAttachment(messageRef, attachmentsFolderRef, part);
            }
        }
    }

}

From source file:de.contentreich.alfresco.repo.email.EMLTransformer.java

private void processPreviewMultiPart(Multipart multipart, Map<String, String> parts)
        throws MessagingException, IOException {
    logger.debug("Processing multipart of type {}", multipart.getContentType());
    // FIXME : Implement strict Depth or breadth first ?
    for (int i = 0, n = multipart.getCount(); i < n; i++) {
        Part part = multipart.getBodyPart(i);
        logger.debug("Processing part name {}, disposition = {}, type type = {}",
                new Object[] { part.getFileName(), part.getDisposition(), part.getContentType() });
        if (part.getContent() instanceof Multipart) {
            processPreviewMultiPart((Multipart) part.getContent(), parts);

        } else if (part.getContentType().contains("text")) {
            String key = part.getContentType().split(";")[0];
            String content = null;
            logger.debug("Add part with content type {} using key {}", part.getContentType(), key);

            if (key.endsWith("html")) {
                // <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
                // Breaks preview !
                content = part.getContent().toString().replaceAll("(?i)(?s)<meta.*charset=[^>]*>", "");
            } else {
                content = part.getContent().toString();
            }/*ww  w . ja v  a 2s. co  m*/
            appendPreviewContent(parts, key, content);

        }

    }
}

From source file:ru.retbansk.utils.scheduled.impl.ReadEmailAndConvertToXmlSpringImpl.java

/**
 * Loads email properties, reads email messages, 
 * converts their multipart bodies into string,
 * send error emails if message doesn't contain valid report and at last returns a reversed Set of the Valid Reports
 * <p><b> deletes messages//w  w  w  .  j  a  v  a 2s.c o m
 * @see #readEmail()
 * @see #convertToXml(HashSet)
 * @see ru.retbansk.utils.scheduled.ReplyManager
 * @return HashSet<DayReport> of the Valid Day Reports
 */
@Override
public HashSet<DayReport> readEmail() throws Exception {

    Properties prop = loadProperties();
    String host = prop.getProperty("host");
    String user = prop.getProperty("user");
    String password = prop.getProperty("password");
    path = prop.getProperty("path");

    // Get system properties
    Properties properties = System.getProperties();

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    // Get a Store object that implements the specified protocol.
    Store store = session.getStore("pop3");

    // Connect to the current host using the specified username and
    // password.
    store.connect(host, user, password);

    // Create a Folder object corresponding to the given name.
    Folder folder = store.getFolder("inbox");

    // Open the Folder.
    folder.open(Folder.READ_WRITE);
    HashSet<DayReport> dayReportSet = new HashSet<DayReport>();
    try {

        // Getting messages from the folder
        Message[] message = folder.getMessages();
        // Reversing the order in the array with the use of Set to make the last one final
        Collections.reverse(Arrays.asList(message));

        // Reading messages.
        String body;
        for (int i = 0; i < message.length; i++) {
            DayReport dayReport = null;
            dayReport = new DayReport();
            dayReport.setPersonId(((InternetAddress) message[i].getFrom()[0]).getAddress());
            Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+3"));
            calendar.setTime(message[i].getSentDate());
            dayReport.setCalendar(calendar);
            dayReport.setSubject(message[i].getSubject());
            List<TaskReport> reportList = null;

            //Release the string from email message body
            body = "";
            Object content = message[i].getContent();
            if (content instanceof java.lang.String) {
                body = (String) content;
            } else if (content instanceof Multipart) {
                Multipart mp = (Multipart) content;

                for (int j = 0; j < mp.getCount(); j++) {
                    Part part = mp.getBodyPart(j);

                    String disposition = part.getDisposition();

                    if (disposition == null) {
                        MimeBodyPart mbp = (MimeBodyPart) part;
                        if (mbp.isMimeType("text/plain")) {
                            body += (String) mbp.getContent();
                        }
                    } else if ((disposition != null)
                            && (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE))) {
                        MimeBodyPart mbp = (MimeBodyPart) part;
                        if (mbp.isMimeType("text/plain")) {
                            body += (String) mbp.getContent();
                        }
                    }
                }
            }

            //Put the string (body of email message) and get list of valid reports else send error
            reportList = new ArrayList<TaskReport>();
            reportList = giveValidReports(body, message[i].getSentDate());
            //Check for valid day report. To be valid it should have size of reportList > 0.
            if (reportList.size() > 0) {
                // adding valid ones to Set
                dayReport.setReportList(reportList);
                dayReportSet.add(dayReport);
            } else {
                // This message doesn't have valid reports. Sending an error reply.
                logger.info("Invalid Day Report detected. Sending an error reply");
                ReplyManager man = new ReplyManagerSimpleImpl();
                man.sendError(dayReport);
            }
            // Delete message
            message[i].setFlag(Flags.Flag.DELETED, true);
        }

    } finally {
        // true tells the mail server to expunge deleted messages.
        folder.close(true);
        store.close();
    }

    return dayReportSet;
}

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.//from w ww .j a  v  a2s. c o m
 * 
 * @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.googlecode.gmail4j.javamail.JavaMailGmailMessage.java

@Override
public List<GmailAttachment> getAttachements() {
    List<GmailAttachment> result = new ArrayList<GmailAttachment>();

    try {/*from w  ww  . j  a  v  a2s.  c  o m*/
        Object content = this.source.getContent();
        if (content instanceof Multipart) {
            Multipart multipart = (Multipart) content;
            for (int i = 0; i < multipart.getCount(); i++) {
                Part bodyPart = multipart.getBodyPart(i);
                if (bodyPart.getDisposition() != null) {
                    if (bodyPart.getDisposition().equalsIgnoreCase(Part.ATTACHMENT)) {
                        result.add(new GmailAttachment(i, bodyPart.getFileName(), bodyPart.getContentType(),
                                bodyPart.getInputStream()));
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new GmailException("Failed to get attachements", e);
    }

    return result;
}

From source file:com.googlecode.gmail4j.javamail.JavaMailGmailMessage.java

@Override
public GmailAttachment getAttachment(int partIndex) {
    GmailAttachment result = null;//w  ww.  j av a 2 s.c  o m

    try {
        Object content = this.source.getContent();
        if (content instanceof Multipart) {
            Multipart multipart = (Multipart) content;
            Part bodyPart = multipart.getBodyPart(partIndex);
            if (bodyPart.getDisposition() != null) {
                if (bodyPart.getDisposition().equalsIgnoreCase(Part.ATTACHMENT)) {
                    result = new GmailAttachment(partIndex, bodyPart.getFileName(), bodyPart.getContentType(),
                            bodyPart.getInputStream());
                }
            }
        } else {
            throw new GmailException("Failed to get attachement with partIndex :" + partIndex);
        }
    } catch (Exception e) {
        throw new GmailException("Failed to get attachement with partIndex :" + partIndex, e);
    }

    return result;
}

From source file:org.campware.cream.modules.scheduledjobs.Pop3Job.java

private String handleMulitipart(Object o, String content, InboxEvent inboxentry) throws Exception {

    Multipart multipart = (Multipart) o;

    for (int k = 0, n = multipart.getCount(); k < n; k++) {

        Part part = multipart.getBodyPart(k);
        String disposition = part.getDisposition();
        MimeBodyPart mbp = (MimeBodyPart) part;

        if ((disposition != null) && (disposition.equals(Part.ATTACHMENT))) {
            log.debug("---------------> Saving File " + part.getFileName() + " " + part.getContent());
            saveAttachment(part, inboxentry);

        } else {//from w w w .ja va2 s  .  c om
            // Check if plain
            if (mbp.isMimeType("text/plain")) {
                log.debug("---------------> Handle plain. ");
                content += "<PRE style=\"font-size: 12px;\">" + (String) part.getContent() + "</PRE>";
                // Check if html
            } else if (mbp.isMimeType("text/html")) {
                log.debug("---------------> Handle plain. ");
                content += (String) part.getContent();
            } else {
                // Special non-attachment cases here of
                // image/gif, text/html, ...
                log.debug("---------------> Special non-attachment cases " + " " + part.getContentType());
                if (mbp.isMimeType("multipart/*")) {
                    Object ob = part.getContent();
                    content = this.handleMulitipart(ob, content, inboxentry) + "\n\n" + content;
                } else {
                    saveAttachment(part, inboxentry);
                }
            }
        }
    }

    return content;
}

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);
}