Example usage for javax.mail BodyPart getInputStream

List of usage examples for javax.mail BodyPart getInputStream

Introduction

In this page you can find the example usage for javax.mail BodyPart getInputStream.

Prototype

public InputStream getInputStream() throws IOException, MessagingException;

Source Link

Document

Return an input stream for this part's "content".

Usage

From source file:net.prhin.mailman.MailMan.java

private static void printFileContents(BodyPart bodyPart) throws IOException, MessagingException {
    InputStream is = bodyPart.getInputStream();

    StringWriter stringWriter = new StringWriter();
    IOUtils.copy(is, stringWriter);//from   ww w  . ja v a  2  s. co  m
    System.out.println("File Content: " + stringWriter.toString());
}

From source file:org.eclipse.ecr.automation.server.jaxrs.io.MultiPartFormRequestReader.java

public static Blob readBlob(HttpServletRequest request, BodyPart part) throws Exception {
    String ctype = part.getContentType();
    String fname = part.getFileName();
    InputStream pin = part.getInputStream();
    final File tmp = File.createTempFile("nx-automation-upload-", ".tmp");
    FileUtils.copyToFile(pin, tmp);// w ww  . jav  a  2  s .  c o m
    FileBlob blob = new FileBlob(tmp, ctype, null, fname, null);
    RequestContext.getActiveContext(request).addRequestCleanupHandler(new RequestCleanupHandler() {
        public void cleanup(HttpServletRequest req) {
            tmp.delete();
        }
    });
    return blob;
}

From source file:org.nuxeo.ecm.automation.server.jaxrs.io.MultiPartFormRequestReader.java

public static Blob readBlob(HttpServletRequest request, BodyPart part) throws Exception {
    String ctype = part.getContentType();
    String fname = part.getFileName();
    InputStream pin = part.getInputStream();
    final File tmp = File.createTempFile("nx-automation-upload-", ".tmp");
    FileUtils.copyToFile(pin, tmp);//from  w w  w .  j  av  a2 s. c o m
    FileBlob blob = new FileBlob(tmp, ctype, null, fname, null);
    RequestContext.getActiveContext(request).addRequestCleanupHandler(new RequestCleanupHandler() {
        @Override
        public void cleanup(HttpServletRequest req) {
            tmp.delete();
        }
    });
    return blob;
}

From source file:org.nuxeo.ecm.automation.jaxrs.io.operations.MultiPartFormRequestReader.java

public static Blob readBlob(HttpServletRequest request, BodyPart part) throws MessagingException, IOException {
    String ctype = part.getContentType();
    String fname = part.getFileName();
    InputStream pin = part.getInputStream();
    final File tmp = Framework.createTempFile("nx-automation-upload-", ".tmp");
    FileUtils.copyToFile(pin, tmp);/*w  w w.j  a v a  2s  .  com*/
    Blob blob = Blobs.createBlob(tmp, ctype, null, fname);
    RequestContext.getActiveContext(request).addRequestCleanupHandler(new RequestCleanupHandler() {
        @Override
        public void cleanup(HttpServletRequest req) {
            tmp.delete();
        }
    });
    return blob;
}

From source file:org.apache.hupa.server.preferences.InImapUserPreferencesStorage.java

/**
 * Opens the IMAP folder and read messages until it founds the magic subject,
 * then gets the attachment which contains the data and return the serialized object stored.
 *//*from ww  w.  ja v a 2 s . co  m*/
protected static Object readUserPreferencesFromIMAP(Log logger, User user, IMAPStore iStore, String folderName,
        String magicType) throws MessagingException, IOException, ClassNotFoundException {
    Folder folder = iStore.getFolder(folderName);
    if (folder.exists()) {
        if (!folder.isOpen()) {
            folder.open(Folder.READ_WRITE);
        }
        Message message = null;
        Message[] msgs = folder.getMessages();
        for (Message msg : msgs) {
            if (magicType.equals(msg.getSubject())) {
                message = msg;
                break;
            }
        }
        if (message != null) {
            Object con = message.getContent();
            if (con instanceof Multipart) {
                Multipart mp = (Multipart) con;
                for (int i = 0; i < mp.getCount(); i++) {
                    BodyPart part = mp.getBodyPart(i);
                    if (part.getContentType().toLowerCase().startsWith(HUPA_DATA_MIME_TYPE)) {
                        ObjectInputStream ois = new ObjectInputStream(part.getInputStream());
                        Object o = ois.readObject();
                        ois.close();
                        logger.info("Returning user preferences of type " + magicType + " from imap folder + "
                                + folderName + " for user " + user);
                        return o;
                    }
                }
            }
        }
    }
    return null;
}

From source file:it.greenvulcano.gvesb.virtual.utils.MimeMessageHelper.java

public static List<Attachment> getMessageAttachments(MimeMessage message) {

    List<Attachment> attachments = new LinkedList<>();

    try {/*ww w. j  a v  a 2  s  .  co  m*/

        Multipart multipartMessage = (Multipart) message.getContent();

        for (int i = 0; i < multipartMessage.getCount(); i++) {
            BodyPart bodyPart = multipartMessage.getBodyPart(i);

            if (bodyPart.getDisposition() != null
                    && bodyPart.getDisposition().equalsIgnoreCase(Part.ATTACHMENT)) {
                byte[] content = IOUtils.toByteArray(bodyPart.getInputStream());
                attachments.add(new Attachment(bodyPart.getContentType(), bodyPart.getFileName(),
                        Base64.encodeBase64String(content)));
            }
        }

    } catch (Exception e) {
        // do nothing
    }

    return attachments;

}

From source file:org.elasticsearch.river.email.EmailToJson.java

public static void saveAttachment(Part part, String destDir)
        throws UnsupportedEncodingException, MessagingException, FileNotFoundException, IOException {
    if (part.isMimeType("multipart/*")) {
        Multipart multipart = (Multipart) part.getContent();

        int partCount = multipart.getCount();
        for (int i = 0; i < partCount; i++) {

            BodyPart bodyPart = multipart.getBodyPart(i);

            String disp = bodyPart.getDisposition();
            if (disp != null
                    && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                InputStream is = bodyPart.getInputStream();
                saveFile(is, destDir, decodeText(bodyPart.getFileName()));
            } else if (bodyPart.isMimeType("multipart/*")) {
                saveAttachment(bodyPart, destDir);
            } else {
                String contentType = bodyPart.getContentType();
                if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) {
                    saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName()));
                }/*from w w w. j ava2s.c om*/
            }
        }
    } else if (part.isMimeType("message/rfc822")) {
        saveAttachment((Part) part.getContent(), destDir);
    }
}

From source file:org.elasticsearch.river.email.EmailToJson.java

public static List<AttachmentInfo> saveAttachmentToWeedFs(Part message, List<AttachmentInfo> attachments,
        EmailRiverConfig config)/*from   w w w. j  a  v  a2  s.  c o m*/
        throws UnsupportedEncodingException, MessagingException, FileNotFoundException, IOException {
    if (attachments == null) {
        attachments = new ArrayList<AttachmentInfo>();
    }
    boolean hasAttachment = false;
    try {
        hasAttachment = isContainAttachment(message);
    } catch (MessagingException e) {
        logger.error("save attachment", e);
    } catch (IOException e) {
        logger.error("save attachment", e);
    }
    if (hasAttachment) {

        if (message.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) message.getContent();

            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {

                BodyPart bodyPart = multipart.getBodyPart(i);

                String disp = bodyPart.getDisposition();
                if (disp != null
                        && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                    InputStream is = bodyPart.getInputStream();

                    BufferedInputStream bis = new BufferedInputStream(is);
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();

                    int len = -1;
                    while ((len = bis.read()) != -1) {
                        bos.write(len);
                    }
                    bos.close();
                    bis.close();

                    byte[] data = bos.toByteArray();
                    String fileId = uploadFileToWeedfs(data, config);
                    if (fileId != null) {
                        AttachmentInfo info = new AttachmentInfo();
                        info.fileId = fileId;
                        info.fileName = decodeText(bodyPart.getFileName());
                        info.fileSize = data.length;
                        attachments.add(info);
                    }

                } else if (bodyPart.isMimeType("multipart/*")) {

                    attachments.addAll(saveAttachmentToWeedFs(bodyPart, attachments, config));

                } else {
                    String contentType = bodyPart.getContentType();
                    if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) {
                        attachments.addAll(saveAttachmentToWeedFs(bodyPart, attachments, config));
                    }
                }
            }
        } else if (message.isMimeType("message/rfc822")) {

            attachments.addAll(saveAttachmentToWeedFs(message, attachments, config));

        }

    }
    return attachments;
}

From source file:com.cws.esolutions.core.utils.EmailUtils.java

/**
 * Processes and sends an email message as generated by the requesting
 * application. This method is utilized with a JNDI datasource.
 *
 * @param dataSource - The email message
 * @param authRequired - <code>true</code> if authentication is required, <code>false</code> otherwise
 * @param authList - If authRequired is true, this must be populated with the auth info
 * @return List - The list of email messages in the mailstore
 * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs during processing
 *//*from w  w w  . j  a v a  2  s .c  o  m*/
public static final synchronized List<EmailMessage> readEmailMessages(final Properties dataSource,
        final boolean authRequired, final List<String> authList) throws MessagingException {
    final String methodName = EmailUtils.CNAME
            + "#readEmailMessages(final Properties dataSource, final boolean authRequired, final List<String> authList) throws MessagingException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("dataSource: {}", dataSource);
        DEBUGGER.debug("authRequired: {}", authRequired);
        DEBUGGER.debug("authList: {}", authList);
    }

    Folder mailFolder = null;
    Session mailSession = null;
    Folder archiveFolder = null;
    List<EmailMessage> emailMessages = null;

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.HOUR, -24);

    final Long TIME_PERIOD = cal.getTimeInMillis();
    final URLName URL_NAME = (authRequired)
            ? new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"),
                    Integer.parseInt(dataSource.getProperty("port")), null, authList.get(0), authList.get(1))
            : new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"),
                    Integer.parseInt(dataSource.getProperty("port")), null, null, null);

    if (DEBUG) {
        DEBUGGER.debug("timePeriod: {}", TIME_PERIOD);
        DEBUGGER.debug("URL_NAME: {}", URL_NAME);
    }

    try {
        // Set up mail session
        mailSession = (authRequired) ? Session.getDefaultInstance(dataSource, new SMTPAuthenticator())
                : Session.getDefaultInstance(dataSource);

        if (DEBUG) {
            DEBUGGER.debug("mailSession: {}", mailSession);
        }

        if (mailSession == null) {
            throw new MessagingException("Unable to configure email services");
        }

        mailSession.setDebug(DEBUG);
        Store mailStore = mailSession.getStore(URL_NAME);
        mailStore.connect();

        if (DEBUG) {
            DEBUGGER.debug("mailStore: {}", mailStore);
        }

        if (!(mailStore.isConnected())) {
            throw new MessagingException("Failed to connect to mail service. Cannot continue.");
        }

        mailFolder = mailStore.getFolder("inbox");
        archiveFolder = mailStore.getFolder("archive");

        if (!(mailFolder.exists())) {
            throw new MessagingException("Requested folder does not exist. Cannot continue.");
        }

        mailFolder.open(Folder.READ_WRITE);

        if ((!(mailFolder.isOpen())) || (!(mailFolder.hasNewMessages()))) {
            throw new MessagingException("Failed to open requested folder. Cannot continue");
        }

        if (!(archiveFolder.exists())) {
            archiveFolder.create(Folder.HOLDS_MESSAGES);
        }

        Message[] mailMessages = mailFolder.getMessages();

        if (mailMessages.length == 0) {
            throw new MessagingException("No messages were found in the provided store.");
        }

        emailMessages = new ArrayList<EmailMessage>();

        for (Message message : mailMessages) {
            if (DEBUG) {
                DEBUGGER.debug("MailMessage: {}", message);
            }

            // validate the message here
            String messageId = message.getHeader("Message-ID")[0];
            Long messageDate = message.getReceivedDate().getTime();

            if (DEBUG) {
                DEBUGGER.debug("messageId: {}", messageId);
                DEBUGGER.debug("messageDate: {}", messageDate);
            }

            // only get emails for the last 24 hours
            // this should prevent us from pulling too
            // many emails
            if (messageDate >= TIME_PERIOD) {
                // process it
                Multipart attachment = (Multipart) message.getContent();
                Map<String, InputStream> attachmentList = new HashMap<String, InputStream>();

                for (int x = 0; x < attachment.getCount(); x++) {
                    BodyPart bodyPart = attachment.getBodyPart(x);

                    if (!(Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()))) {
                        continue;
                    }

                    attachmentList.put(bodyPart.getFileName(), bodyPart.getInputStream());
                }

                List<String> toList = new ArrayList<String>();
                List<String> ccList = new ArrayList<String>();
                List<String> bccList = new ArrayList<String>();
                List<String> fromList = new ArrayList<String>();

                for (Address from : message.getFrom()) {
                    fromList.add(from.toString());
                }

                if ((message.getRecipients(RecipientType.TO) != null)
                        && (message.getRecipients(RecipientType.TO).length != 0)) {
                    for (Address to : message.getRecipients(RecipientType.TO)) {
                        toList.add(to.toString());
                    }
                }

                if ((message.getRecipients(RecipientType.CC) != null)
                        && (message.getRecipients(RecipientType.CC).length != 0)) {
                    for (Address cc : message.getRecipients(RecipientType.CC)) {
                        ccList.add(cc.toString());
                    }
                }

                if ((message.getRecipients(RecipientType.BCC) != null)
                        && (message.getRecipients(RecipientType.BCC).length != 0)) {
                    for (Address bcc : message.getRecipients(RecipientType.BCC)) {
                        bccList.add(bcc.toString());
                    }
                }

                EmailMessage emailMessage = new EmailMessage();
                emailMessage.setMessageTo(toList);
                emailMessage.setMessageCC(ccList);
                emailMessage.setMessageBCC(bccList);
                emailMessage.setEmailAddr(fromList);
                emailMessage.setMessageAttachments(attachmentList);
                emailMessage.setMessageDate(message.getSentDate());
                emailMessage.setMessageSubject(message.getSubject());
                emailMessage.setMessageBody(message.getContent().toString());
                emailMessage.setMessageSources(message.getHeader("Received"));

                if (DEBUG) {
                    DEBUGGER.debug("emailMessage: {}", emailMessage);
                }

                emailMessages.add(emailMessage);

                if (DEBUG) {
                    DEBUGGER.debug("emailMessages: {}", emailMessages);
                }
            }

            // archive it
            archiveFolder.open(Folder.READ_WRITE);

            if (archiveFolder.isOpen()) {
                mailFolder.copyMessages(new Message[] { message }, archiveFolder);
                message.setFlag(Flags.Flag.DELETED, true);
            }
        }
    } catch (IOException iox) {
        throw new MessagingException(iox.getMessage(), iox);
    } catch (MessagingException mex) {
        throw new MessagingException(mex.getMessage(), mex);
    } finally {
        try {
            if ((mailFolder != null) && (mailFolder.isOpen())) {
                mailFolder.close(true);
            }

            if ((archiveFolder != null) && (archiveFolder.isOpen())) {
                archiveFolder.close(false);
            }
        } catch (MessagingException mx) {
            ERROR_RECORDER.error(mx.getMessage(), mx);
        }
    }

    return emailMessages;
}

From source file:org.mule.module.http.internal.HttpParser.java

public static Collection<HttpPart> parseMultipartContent(InputStream content, String contentType)
        throws IOException {
    MimeMultipart mimeMultipart = null;/*from   w ww.j ava 2 s .  c om*/
    List<HttpPart> parts = Lists.newArrayList();

    try {
        mimeMultipart = new MimeMultipart(new ByteArrayDataSource(content, contentType));
    } catch (MessagingException e) {
        throw new IOException(e);
    }

    try {
        int partCount = mimeMultipart.getCount();

        for (int i = 0; i < partCount; i++) {
            BodyPart part = mimeMultipart.getBodyPart(i);

            String filename = part.getFileName();
            String partName = filename;
            String[] contentDispositions = part.getHeader(CONTENT_DISPOSITION_PART_HEADER);
            if (contentDispositions != null) {
                String contentDisposition = contentDispositions[0];
                if (contentDisposition.contains(NAME_ATTRIBUTE)) {
                    partName = contentDisposition.substring(
                            contentDisposition.indexOf(NAME_ATTRIBUTE) + NAME_ATTRIBUTE.length() + 2);
                    partName = partName.substring(0, partName.indexOf("\""));
                }
            }
            HttpPart httpPart = new HttpPart(partName, filename, IOUtils.toByteArray(part.getInputStream()),
                    part.getContentType(), part.getSize());

            Enumeration<Header> headers = part.getAllHeaders();

            while (headers.hasMoreElements()) {
                Header header = headers.nextElement();
                httpPart.addHeader(header.getName(), header.getValue());
            }
            parts.add(httpPart);
        }
    } catch (MessagingException e) {
        throw new IOException(e);
    }

    return parts;
}