Example usage for javax.mail BodyPart getDisposition

List of usage examples for javax.mail BodyPart getDisposition

Introduction

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

Prototype

public String getDisposition() throws MessagingException;

Source Link

Document

Return the disposition of this part.

Usage

From source file:de.saly.elasticsearch.importer.imap.support.IndexableMailMessage.java

public static IndexableMailMessage fromJavaMailMessage(final Message jmm, final boolean withTextContent,
        final boolean withHtmlContent, final boolean preferHtmlContent, final boolean withAttachments,
        final boolean stripTags, List<String> headersToFields) throws MessagingException, IOException {
    final IndexableMailMessage im = new IndexableMailMessage();

    @SuppressWarnings("unchecked")
    final Enumeration<Header> allHeaders = jmm.getAllHeaders();

    final Set<IndexableHeader> headerList = new HashSet<IndexableHeader>();
    while (allHeaders.hasMoreElements()) {
        final Header h = allHeaders.nextElement();
        headerList.add(new IndexableHeader(h.getName(), h.getValue()));
    }//  w  ww  .ja v  a  2 s  .c  o m

    im.setHeaders(headerList.toArray(new IndexableHeader[headerList.size()]));

    im.setSelectedHeaders(extractHeaders(im.getHeaders(), headersToFields));

    if (jmm.getFolder() instanceof POP3Folder) {
        im.setPopId(((POP3Folder) jmm.getFolder()).getUID(jmm));
        im.setMailboxType("POP");

    } else {
        im.setMailboxType("IMAP");
    }

    if (jmm.getFolder() instanceof UIDFolder) {
        im.setUid(((UIDFolder) jmm.getFolder()).getUID(jmm));
    }

    im.setFolderFullName(jmm.getFolder().getFullName());

    im.setFolderUri(jmm.getFolder().getURLName().toString());

    im.setContentType(jmm.getContentType());
    im.setSubject(jmm.getSubject());
    im.setSize(jmm.getSize());
    im.setSentDate(jmm.getSentDate());

    if (jmm.getReceivedDate() != null) {
        im.setReceivedDate(jmm.getReceivedDate());
    }

    if (jmm.getFrom() != null && jmm.getFrom().length > 0) {
        im.setFrom(Address.fromJavaMailAddress(jmm.getFrom()[0]));
    }

    if (jmm.getRecipients(RecipientType.TO) != null) {
        im.setTo(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.TO)));
    }

    if (jmm.getRecipients(RecipientType.CC) != null) {
        im.setCc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.CC)));
    }

    if (jmm.getRecipients(RecipientType.BCC) != null) {
        im.setBcc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.BCC)));
    }

    if (withTextContent) {

        // try {

        String textContent = getText(jmm, 0, preferHtmlContent);

        if (stripTags) {
            textContent = stripTags(textContent);
        }

        im.setTextContent(textContent);
        // } catch (final Exception e) {
        // logger.error("Unable to retrieve text content for message {} due to {}",
        // e, ((MimeMessage) jmm).getMessageID(), e);
        // }
    }

    if (withHtmlContent) {

        // try {

        String htmlContent = getText(jmm, 0, true);

        im.setHtmlContent(htmlContent);
        // } catch (final Exception e) {
        // logger.error("Unable to retrieve text content for message {} due to {}",
        // e, ((MimeMessage) jmm).getMessageID(), e);
        // }
    }

    if (withAttachments) {

        try {
            final Object content = jmm.getContent();

            // look for attachments
            if (jmm.isMimeType("multipart/*") && content instanceof Multipart) {
                List<ESAttachment> attachments = new ArrayList<ESAttachment>();

                final Multipart multipart = (Multipart) content;

                for (int i = 0; i < multipart.getCount(); i++) {
                    final BodyPart bodyPart = multipart.getBodyPart(i);
                    if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())
                            && !StringUtils.isNotBlank(bodyPart.getFileName())) {
                        continue; // dealing with attachments only
                    }
                    final InputStream is = bodyPart.getInputStream();
                    final byte[] bytes = IOUtils.toByteArray(is);
                    IOUtils.closeQuietly(is);
                    attachments.add(new ESAttachment(bodyPart.getContentType(), bytes, bodyPart.getFileName()));
                }

                if (!attachments.isEmpty()) {
                    im.setAttachments(attachments.toArray(new ESAttachment[attachments.size()]));
                    im.setAttachmentCount(im.getAttachments().length);
                    attachments.clear();
                    attachments = null;
                }

            }
        } catch (final Exception e) {
            logger.error(
                    "Error indexing attachments (message will be indexed but without attachments) due to {}", e,
                    e.toString());
        }

    }

    im.setFlags(IMAPUtils.toStringArray(jmm.getFlags()));
    im.setFlaghashcode(jmm.getFlags().hashCode());

    return im;
}

From source file:org.openhie.openempi.service.MailEngineTest.java

public void testSendMessageWithAttachment() throws Exception {
    final String ATTACHMENT_NAME = "boring-attachment.txt";

    //mock smtp server
    Wiser wiser = new Wiser();
    int port = 2525 + (int) (Math.random() * 100);
    mailSender.setPort(port);/*from ww w .  ja va  2 s.  co m*/
    wiser.setPort(port);
    wiser.start();

    Date dte = new Date();
    String emailSubject = "grepster testSendMessageWithAttachment: " + dte;
    String emailBody = "Body of the grepster testSendMessageWithAttachment message sent at: " + dte;

    ClassPathResource cpResource = new ClassPathResource("/test-attachment.txt");
    mailEngine.sendMessage(new String[] { "foo@bar.com" }, mailMessage.getFrom(), cpResource, emailBody,
            emailSubject, ATTACHMENT_NAME);

    wiser.stop();
    assertTrue(wiser.getMessages().size() == 1);
    WiserMessage wm = wiser.getMessages().get(0);
    MimeMessage mm = wm.getMimeMessage();

    Object o = wm.getMimeMessage().getContent();
    assertTrue(o instanceof MimeMultipart);
    MimeMultipart multi = (MimeMultipart) o;
    int numOfParts = multi.getCount();

    boolean hasTheAttachment = false;
    for (int i = 0; i < numOfParts; i++) {
        BodyPart bp = multi.getBodyPart(i);
        String disp = bp.getDisposition();
        if (disp == null) { //the body of the email
            Object innerContent = bp.getContent();
            MimeMultipart innerMulti = (MimeMultipart) innerContent;
            assertEquals(emailBody, innerMulti.getBodyPart(0).getContent());
        } else if (disp.equals(Part.ATTACHMENT)) { //the attachment to the email
            hasTheAttachment = true;
            assertEquals(ATTACHMENT_NAME, bp.getFileName());
        } else {
            fail("Did not expect to be able to get here.");
        }
    }
    assertTrue(hasTheAttachment);
    assertEquals(emailSubject, mm.getSubject());
}

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  ww  w  . j a  va  2 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.openmrs.contrib.metadatarepository.service.MailEngineTest.java

@Test
public void testSendMessageWithAttachment() throws Exception {
    final String ATTACHMENT_NAME = "boring-attachment.txt";

    //mock smtp server
    Wiser wiser = new Wiser();
    int port = 2525 + (int) (Math.random() * 100);
    mailSender.setPort(port);// ww w. j  a  v  a 2s .  com
    wiser.setPort(port);
    wiser.start();

    Date dte = new Date();
    String emailSubject = "grepster testSendMessageWithAttachment: " + dte;
    String emailBody = "Body of the grepster testSendMessageWithAttachment message sent at: " + dte;

    ClassPathResource cpResource = new ClassPathResource("/test-attachment.txt");
    // a null from should work
    mailEngine.sendMessage(new String[] { "foo@bar.com" }, null, cpResource, emailBody, emailSubject,
            ATTACHMENT_NAME);

    mailEngine.sendMessage(new String[] { "foo@bar.com" }, mailMessage.getFrom(), cpResource, emailBody,
            emailSubject, ATTACHMENT_NAME);

    wiser.stop();
    // one without and one with from
    assertTrue(wiser.getMessages().size() == 2);

    WiserMessage wm = wiser.getMessages().get(0);
    MimeMessage mm = wm.getMimeMessage();

    Object o = wm.getMimeMessage().getContent();
    assertTrue(o instanceof MimeMultipart);
    MimeMultipart multi = (MimeMultipart) o;
    int numOfParts = multi.getCount();

    boolean hasTheAttachment = false;
    for (int i = 0; i < numOfParts; i++) {
        BodyPart bp = multi.getBodyPart(i);
        String disp = bp.getDisposition();
        if (disp == null) { //the body of the email
            Object innerContent = bp.getContent();
            MimeMultipart innerMulti = (MimeMultipart) innerContent;
            assertEquals(emailBody, innerMulti.getBodyPart(0).getContent());
        } else if (disp.equals(Part.ATTACHMENT)) { //the attachment to the email
            hasTheAttachment = true;
            assertEquals(ATTACHMENT_NAME, bp.getFileName());
        } else {
            fail("Did not expect to be able to get here.");
        }
    }
    assertTrue(hasTheAttachment);
    assertEquals(emailSubject, mm.getSubject());
}

From source file:ch.algotrader.util.mail.EmailTransformer.java

/**
 * Parses any {@link Multipart} instances that contains attachments
 *
 * Will create the respective {@link EmailFragment}s representing those attachments.
 * @throws MessagingException//from  w w  w  . jav  a 2s .  c  o m
 */
public void handleMultipart(Multipart multipart, List<EmailFragment> emailFragments) throws MessagingException {

    final int count = multipart.getCount();

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

        BodyPart bodyPart = multipart.getBodyPart(i);
        String filename = bodyPart.getFileName();
        String disposition = bodyPart.getDisposition();

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

        if (disposition == null) {

            //ignore message body

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

            try {
                try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        BufferedInputStream bis = new BufferedInputStream(bodyPart.getInputStream())) {

                    IOUtils.copy(bis, bos);

                    emailFragments.add(new EmailFragment(filename, bos.toByteArray()));

                    if (LOGGER.isInfoEnabled()) {
                        LOGGER.info(String.format("processing file: %s", new Object[] { filename }));
                    }

                }

            } catch (IOException e) {
                throw new MessagingException("error processing streams", e);
            }

        } else {
            throw new MessagingException("unkown disposition " + disposition);
        }
    }
}

From source file:com.zotoh.crypto.MICUte.java

private static Object fromMP(Multipart mp) throws Exception {
    ContentType ct = new ContentType(mp.getContentType());
    BodyPart bp;
    Object contents;//from  w w  w  .  j av  a 2  s  . c  o  m
    Object rc = null;
    int count = mp.getCount();

    if ("multipart/mixed".equalsIgnoreCase(ct.getBaseType())) {
        if (count > 0) {
            bp = mp.getBodyPart(0);
            contents = bp.getContent();

            // check for EDI payload sent as attachment
            String ctype = bp.getContentType();
            boolean getNextPart = false;

            if (ctype.indexOf("text/plain") >= 0) {
                if (contents instanceof String) {
                    String bodyText = "This is a generated cryptographic message in MIME format";
                    if (((String) contents).startsWith(bodyText)) {
                        getNextPart = true;
                    }
                }

                if (!getNextPart) {
                    // check for a content disposition
                    // if disposition type is attachment, then this is a doc
                    getNextPart = true;
                    String disp = bp.getDisposition();
                    if (disp != null && disp.toLowerCase().equals("attachment"))
                        getNextPart = false;
                }
            }

            if ((count >= 2) && getNextPart) {
                bp = mp.getBodyPart(1);
                contents = bp.getContent();
            }

            if (contents instanceof String) {
                rc = asBytes((String) contents);
            } else if (contents instanceof byte[]) {
                rc = contents;
            } else if (contents instanceof InputStream) {
                rc = contents;
            } else {
                String cn = contents == null ? "null" : contents.getClass().getName();
                throw new Exception("Unsupport MIC object: " + cn);
            }
        }
    } else if (count > 0) {
        bp = mp.getBodyPart(0);
        contents = bp.getContent();

        if (contents instanceof String) {
            rc = asBytes((String) contents);
        } else if (contents instanceof byte[]) {
            rc = contents;
        } else if (contents instanceof InputStream) {
            rc = contents;
        } else {
            String cn = contents == null ? "null" : contents.getClass().getName();
            throw new Exception("Unsupport MIC object: " + cn);
        }
    }

    return rc;
}

From source file:com.crawlersick.nettool.GetattchmentFromMail1.java

public boolean fetchmailforattch() throws IOException, MessagingException {
    boolean fetchtest = false;

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

    try {//from  w  w w . j av a2 s  .  c o m
        Session session = Session.getInstance(props, null);
        Store store = session.getStore();
        store.connect(IMapHost, MailId, MailPassword);
        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_ONLY);
        totalmailcount = inbox.getMessageCount();

        Message msg = null;
        for (int i = totalmailcount; i > 0; i--) {
            fromadd = "";
            msg = inbox.getMessage(i);
            Address[] in = msg.getFrom();
            for (Address address : in) {
                fromadd = address.toString() + fromadd;
                //System.out.println("FROM:" + address.toString());
            }
            if (fromadd.matches("admin@cronmailservice.appspotmail.com") && msg.getSubject().matches(
                    "ThanksToTsukuba_World-on-my-shoulders-as-I-run-back-to-this-8-Mile-Road_cronmailservice"))
                break;
        }

        if (fromadd.equals("'")) {
            log.log(Level.SEVERE, "Error: no related mail found!" + this.MailId);
            return fetchtest;
        }

        //    Multipart mp = (Multipart) msg.getContent();
        //  BodyPart bp = mp.getBodyPart(0);
        sentdate = msg.getSentDate().toString();

        subject = msg.getSubject();

        Content = msg.getContent().toString();

        log.log(Level.INFO, Content);
        log.log(Level.INFO, sentdate);
        localIntent.putExtra("213123", "Got Server latest update at : " + sentdate + " , Reading the Data...");
        LocalBroadcastManager.getInstance(myis).sendBroadcast(localIntent);

        Multipart multipart = (Multipart) msg.getContent();
        for (int i = 0; i < multipart.getCount(); i++) {
            BodyPart bodyPart = multipart.getBodyPart(i);
            if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && (bodyPart.getFileName() == null
                    || !bodyPart.getFileName().equals("dataforvgendwithudp.gzip"))) {
                continue; // dealing with attachments only
            }
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            InputStream is = bodyPart.getInputStream();
            //validvgbinary = IOUtils.toByteArray(is);
            int nRead;
            byte[] data = new byte[5000000];

            while ((nRead = is.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }

            buffer.flush();

            validvgbinary = buffer.toByteArray();
            break;
        }

        fetchtest = true;
    } catch (Exception mex) {
        mex.printStackTrace();

    }

    return fetchtest;
}

From source file:gov.nih.nci.cacis.nav.DefaultNotificationValidator.java

private void validateAttachmentBodyPart(BodyPart bodyPart) throws NotificationValidationException {
    try {//  w  w w  .  ja  va  2 s . c  o  m
        final String disposition = bodyPart.getDisposition();
        if (StringUtils.isEmpty(disposition) || !disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
            throw new NotificationValidationException(ERR_INVALID_ATTMNT_PART_MSG);
        }

        if (!bodyPart.isMimeType("application/xml")) {
            throw new NotificationValidationException(ERR_INVALID_ATTMNT_MIMETYPE_MSG);
        }
        validateAttachmentFileName(bodyPart.getFileName());
    } catch (MessagingException e) {
        throw new NotificationValidationException(ERR_INVALID_MULTIPART_MSG, e);
    }
}

From source file:org.apache.oozie.action.email.TestEmailActionExecutor.java

private void assertAttachment(String attachtag, int attachCount, String content1, String content2)
        throws Exception {
    sendAndReceiveEmail(attachtag);/*ww w.  j  a  v a  2s  .  c  o m*/
    MimeMessage retMeg = server.getReceivedMessages()[0];
    Multipart retParts = (Multipart) (retMeg.getContent());
    int numAttach = 0;
    for (int i = 0; i < retParts.getCount(); i++) {
        BodyPart bp = retParts.getBodyPart(i);
        String disp = bp.getDisposition();
        String retValue = IOUtils.toString(bp.getInputStream());
        if (disp != null && (disp.equals(BodyPart.ATTACHMENT))) {
            assertTrue(retValue.equals(content1) || retValue.equals(content2));
            numAttach++;
        } else {
            assertEquals("This is a test mail", retValue);
        }
    }
    assertEquals(attachCount, numAttach);
}

From source file:com.glaf.mail.business.MailBean.java

/**
 * ??/*  ww w  .j a  va  2  s . co m*/
 * 
 * @param part
 * @return
 * @throws MessagingException
 * @throws IOException
 */
public boolean isContainAttch(Part part) throws MessagingException, IOException {
    boolean flag = false;
    if (part.isMimeType("multipart/*")) {
        Multipart multipart = (Multipart) part.getContent();
        int count = multipart.getCount();
        for (int i = 0; i < count; i++) {
            BodyPart bodypart = multipart.getBodyPart(i);
            String dispostion = bodypart.getDisposition();
            if ((dispostion != null)
                    && (dispostion.equals(Part.ATTACHMENT) || dispostion.equals(Part.INLINE))) {
                flag = true;
            } else if (bodypart.isMimeType("multipart/*")) {
                flag = isContainAttch(bodypart);
            } else {
                String contentType = bodypart.getContentType();
                if (contentType.toLowerCase().indexOf("appliaction") != -1) {
                    flag = true;
                }
                if (contentType.toLowerCase().indexOf("name") != -1) {
                    flag = true;
                }
            }
        }
    } else if (part.isMimeType("message/rfc822")) {
        flag = isContainAttch((Part) part.getContent());
    }

    return flag;
}