Example usage for javax.mail Multipart getBodyPart

List of usage examples for javax.mail Multipart getBodyPart

Introduction

In this page you can find the example usage for javax.mail Multipart getBodyPart.

Prototype

public synchronized BodyPart getBodyPart(int index) throws MessagingException 

Source Link

Document

Get the specified Part.

Usage

From source file:ru.codemine.ccms.mail.EmailAttachmentExtractor.java

public void saveAllAttachment() {
    String protocol = ssl ? "imaps" : "imap";

    Properties props = new Properties();
    props.put("mail.store.protocol", protocol);

    try {/*from  w w  w  . ja v  a2  s  . c  o m*/
        Session session = Session.getInstance(props);
        Store store = session.getStore();
        store.connect(host, port, username, password);

        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_WRITE);

        for (Message msg : inbox.getMessages()) {
            if (!msg.isSet(Flags.Flag.SEEN)) {
                String fileNamePrefix = settingsService.getStorageEmailPath() + "msg-" + msg.getMessageNumber();
                Multipart multipart = (Multipart) msg.getContent();
                for (int i = 0; i < multipart.getCount(); i++) {
                    BodyPart bodyPart = multipart.getBodyPart(i);
                    if (Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())
                            && StringUtils.isNotEmpty(bodyPart.getFileName())) {
                        MimeBodyPart mimimi = (MimeBodyPart) bodyPart; // =(^.^)= 
                        mimimi.saveFile(fileNamePrefix + MimeUtility.decodeText(bodyPart.getFileName()));
                        msg.setFlag(Flags.Flag.SEEN, true);
                    }
                }
            }
        }
    } catch (IOException | MessagingException e) {
        log.error("? ? ?,  : "
                + e.getMessage());
    }

}

From source file:org.jtalks.tests.jcommune.mail.mailtrap.MailtrapMail.java

private String tryToGetLink(String recipient) {
    Gson gson = new Gson();
    MessageDto[] messages;//from ww w .ja v  a2  s.com
    String link = null;

    messages = gson.fromJson(MailtrapClient.getMessages(), MessageDto[].class);

    List<Metadata> metadataList = getMetadataList(messages);

    String id = NOT_FOUND_ID;
    DateTime createdAt = null;
    for (Metadata metadata : metadataList) {
        if (!recipient.equals(metadata.getRecipient())) {
            continue;
        }
        if (id.equals(NOT_FOUND_ID) || metadata.getDateTime().isAfter(createdAt)) {
            id = metadata.getId();
        }
    }
    if (id.equals(NOT_FOUND_ID)) {
        return link;
    }

    MessageDto messageDto = gson.fromJson(MailtrapClient.getMessage(id), MessageDto.class);

    try {
        String source = messageDto.getMessage().getSource();

        MimeMessage message = new MimeMessage(Session.getInstance(new Properties()),
                (new ByteArrayInputStream(source.getBytes())));
        Multipart multipart = (Multipart) message.getContent();
        Multipart multipart1 = (Multipart) multipart.getBodyPart(0).getContent();
        Multipart multipart2 = (Multipart) multipart1.getBodyPart(0).getContent();
        String escapedText = (String) multipart2.getBodyPart(0).getContent();
        String text = StringEscapeUtils.unescapeHtml(escapedText);
        Matcher matcher = Pattern.compile("(http://.*/activate/.*)[\\s]").matcher(text);
        if (matcher.find()) {
            link = matcher.group(1);
        }
    } catch (MessagingException | IOException e) {
        LOGGER.warn("Problem occurred while grabbing activation link from Mailtrap", e);
    }
    return link;
}

From source file:com.glaf.mail.MxMailHelper.java

public void processMultipart(Multipart mp, Mail mail) throws Exception {
    for (int i = 0; i < mp.getCount(); i++) {
        String filename = (mp.getBodyPart(i)).getFileName();
        if (filename == null) {
            this.processPart(mp.getBodyPart(i), mail);
        }/*  ww w . j a  v  a 2  s .  c  o m*/
    }
}

From source file:mx.uaq.facturacion.enlace.EmailParserUtils.java

/**
 * Parses any {@link Multipart} instances that contain text or Html attachments,
 * {@link InputStream} instances, additional instances of {@link Multipart}
 * or other attached instances of {@link javax.mail.Message}.
 *
 * Will create the respective {@link EmailFragment}s representing those attachments.
 *
 * Instances of {@link javax.mail.Message} are delegated to
 * {@link #handleMessage(File, javax.mail.Message, List)}. Further instances
 * of {@link Multipart} are delegated to
 * {@link #handleMultipart(File, Multipart, javax.mail.Message, List)}.
 *
 * @param directory Must not be null//w ww  . j  a  v  a2  s  .c  o  m
 * @param multipart Must not be null
 * @param mailMessage Must not be null
 * @param emailFragments Must not be null
 */
public static void handleMultipart(File directory, Multipart multipart, javax.mail.Message mailMessage,
        List<EmailFragment> emailFragments) {

    Assert.notNull(directory, "The directory must not be null.");
    Assert.notNull(multipart, "The multipart object to be parsed must not be null.");
    Assert.notNull(mailMessage, "The mail message to be parsed must not be null.");
    Assert.notNull(emailFragments, "The collection of emailfragments must not be null.");

    final int count;

    try {
        count = multipart.getCount();

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info(String.format("Number of enclosed BodyPart objects: %s.", count));
        }

    } catch (MessagingException e) {
        throw new IllegalStateException("Error while retrieving the number of enclosed BodyPart objects.", e);
    }

    for (int i = 0; i < count; i++) {

        final BodyPart bp;

        try {
            bp = multipart.getBodyPart(i);
        } catch (MessagingException e) {
            throw new IllegalStateException("Error while retrieving body part.", e);
        }

        final String contentType;
        String filename;
        final String disposition;
        final String subject;

        try {

            contentType = bp.getContentType();
            filename = bp.getFileName();
            disposition = bp.getDisposition();
            subject = mailMessage.getSubject();

            if (filename == null && bp instanceof MimeBodyPart) {
                filename = ((MimeBodyPart) bp).getContentID();
            }

        } catch (MessagingException e) {
            throw new IllegalStateException("Unable to retrieve body part meta data.", e);
        }

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info(String.format(
                    "BodyPart - Content Type: '%s', filename: '%s', disposition: '%s', subject: '%s'",
                    new Object[] { contentType, filename, disposition, subject }));
        }

        if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
            LOGGER.info(String.format("Handdling attachment '%s', type: '%s'", filename, contentType));
        }

        final Object content;

        try {
            content = bp.getContent();
        } catch (IOException e) {
            throw new IllegalStateException("Error while retrieving the email contents.", e);
        } catch (MessagingException e) {
            throw new IllegalStateException("Error while retrieving the email contents.", e);
        }

        if (content instanceof String) {

            if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
                emailFragments.add(new EmailFragment(directory, i + "-" + filename, content));
                LOGGER.info(String.format("Handdling attachment '%s', type: '%s'", filename, contentType));
            } else {

                final String textFilename;
                final ContentType ct;

                try {
                    ct = new ContentType(contentType);
                } catch (ParseException e) {
                    throw new IllegalStateException("Error while parsing content type '" + contentType + "'.",
                            e);
                }

                if ("text/plain".equalsIgnoreCase(ct.getBaseType())) {
                    textFilename = "message.txt";
                } else if ("text/html".equalsIgnoreCase(ct.getBaseType())) {
                    textFilename = "message.html";
                } else {
                    textFilename = "message.other";
                }

                emailFragments.add(new EmailFragment(directory, textFilename, content));
            }

        } else if (content instanceof InputStream) {

            final InputStream inputStream = (InputStream) content;
            final ByteArrayOutputStream bis = new ByteArrayOutputStream();

            try {
                IOUtils.copy(inputStream, bis);
            } catch (IOException e) {
                throw new IllegalStateException(
                        "Error while copying input stream to the ByteArrayOutputStream.", e);
            }

            emailFragments.add(new EmailFragment(directory, filename, bis.toByteArray()));

        } else if (content instanceof javax.mail.Message) {
            handleMessage(directory, (javax.mail.Message) content, emailFragments);
        } else if (content instanceof Multipart) {
            final Multipart mp2 = (Multipart) content;
            handleMultipart(directory, mp2, mailMessage, emailFragments);
        } else {
            throw new IllegalStateException("Content type not handled: " + content.getClass().getSimpleName());
        }
    }
}

From source file:eu.openanalytics.rsb.EmailDepositITCase.java

private BodyPart getMailBodyPart(final Multipart parts, final String contentType) throws MessagingException {
    for (int i = 0; i < parts.getCount(); i++) {
        final BodyPart part = parts.getBodyPart(i);
        if (StringUtils.startsWith(part.getContentType(), contentType)) {
            return part;
        }/*ww  w.  ja v a 2s  .  c o  m*/
    }
    throw new IllegalStateException("No part of type " + contentType + " found");
}

From source file:org.apache.synapse.transport.mail.MailUtils.java

public InputStream getInputStream(Object message) {
    try {/*from  w  w w . ja v a  2  s  .  c  o  m*/
        if (message instanceof MimeMessage) {
            MimeMessage msg = (MimeMessage) message;
            if (msg.getContent() instanceof Multipart) {
                MimeBodyPart firstTextPart = null;

                Multipart mp = (Multipart) msg.getContent();
                for (int i = 0; i < mp.getCount(); i++) {
                    MimeBodyPart mbp = (MimeBodyPart) mp.getBodyPart(i);
                    String contType = mbp.getContentType();

                    if (contType != null && (contType.indexOf(SOAP11Constants.SOAP_11_CONTENT_TYPE) != -1
                            || contType.indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) != -1)) {
                        // this part is a SOAP 11 or 12 payload, treat this as the message
                        return mbp.getInputStream();
                    } else if (mbp == null && contType.indexOf("plain/text") != -1) {
                        firstTextPart = mbp;
                    }
                }
                // if a soap 11 or soap12 payload was not found, treat first text part as message
                return firstTextPart.getInputStream();

            } else {
                return ((Message) message).getInputStream();
            }
        }
    } catch (Exception e) {
        handleException("Error creating an input stream to : " + ((Message) message).getMessageNumber(), e);
    }
    return null;
}

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

/**
 * Add attachments to an imported mail./*from w  w w.  j av  a 2 s . c  om*/
 */
public static void addAttachments(String token, com.ikon.bean.Mail mail, Part p, String userId)
        throws MessagingException, IOException, UnsupportedMimeTypeException, FileSizeExceededException,
        UserQuotaExceededException, VirusDetectedException, ItemExistsException, PathNotFoundException,
        AccessDeniedException, RepositoryException, DatabaseException, ExtensionException, AutomationException {
    if (p.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) p.getContent();
        int count = mp.getCount();

        for (int i = 1; i < count; i++) {
            BodyPart bp = mp.getBodyPart(i);

            if (bp.getFileName() != null) {
                String name = MimeUtility.decodeText(bp.getFileName());
                String fileName = FileUtils.getFileName(name);
                String fileExtension = FileUtils.getFileExtension(name);
                String testName = name;

                // Test if already exists a document with the same name in the mail
                for (int j = 1; OKMRepository.getInstance().hasNode(token,
                        mail.getPath() + "/" + testName); j++) {
                    // log.info("Trying with: {}", testName);
                    testName = fileName + " (" + j + ")." + fileExtension;
                }

                Document attachment = new Document();
                String mimeType = MimeTypeConfig.mimeTypes.getContentType(bp.getFileName().toLowerCase());
                attachment.setMimeType(mimeType);
                attachment.setPath(mail.getPath() + "/" + testName);
                InputStream is = bp.getInputStream();

                if (Config.REPOSITORY_NATIVE) {
                    new DbDocumentModule().create(token, attachment, is, bp.getSize(), userId);
                } else {
                    new JcrDocumentModule().create(token, attachment, is, userId);
                }

                is.close();
            }
        }
    }
}

From source file:com.adaptris.core.services.mime.FlattenMimeParts.java

private List<BodyPart> extract(Multipart m) throws Exception {
    List<BodyPart> parts = new ArrayList<>();
    for (int i = 0; i < m.getCount(); i++) {
        BodyPart p = m.getBodyPart(i);
        if (p.isMimeType("multipart/*")) {
            parts.addAll(extract((Multipart) p.getContent()));
        } else {//from  w  ww.  j a  va2s .co m
            parts.add(p);
        }
    }
    return parts;
}

From source file:org.xwiki.administration.test.ui.ResetPasswordIT.java

protected BodyPart getPart(Multipart messageContent, String mimeType) throws Exception {
    for (int i = 0; i < messageContent.getCount(); i++) {
        BodyPart part = messageContent.getBodyPart(i);

        if (part.isMimeType(mimeType)) {
            return part;
        }/*from   w ww. j  a v  a2  s .c o  m*/

        if (part.isMimeType("multipart/related") || part.isMimeType("multipart/alternative")
                || part.isMimeType("multipart/mixed")) {
            BodyPart out = getPart((Multipart) part.getContent(), mimeType);
            if (out != null) {
                return out;
            }
        }
    }
    return null;
}

From source file:com.zextras.modules.chat.server.history.HistoryMailManager.java

private void updateConversation(List<ChatMessage> messages, Chat chat, Account self,
        SpecificAddress participant) throws ZimbraException, MessagingException, IOException {
    ChatMessage conversation = new ChatMessage(new SpecificAddress(self.getName()), participant,
            new Date(chat.getChangeDate()));

    Multipart multipart = (Multipart) chat.getMimeMessage().getDataHandler().getContent();

    for (int i = 0; i < multipart.getCount(); i++) {
        if (multipart.getBodyPart(i).isMimeType("text/plain")) {
            conversation.setBody(multipart.getBodyPart(i).getDataHandler().getContent().toString());
        } else {//from  www  .j a v a 2 s. co m
            conversation.setHtmlBody(multipart.getBodyPart(i).getDataHandler().getContent().toString());
        }
    }

    ConversationBuilder conversationBuilder = new ConversationBuilder(self.getName(), conversation,
            mOpenUserProvider);

    for (ChatMessage message : messages) {
        conversationBuilder.addMessage(message, new Date(chat.getDate()),
                self.getAccountTimeZone().getTimeZone());
    }
    conversationBuilder.closeHtml();
    createMessageWriter(conversationBuilder).updateExistingChat(chat);
}