Example usage for javax.mail Part ATTACHMENT

List of usage examples for javax.mail Part ATTACHMENT

Introduction

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

Prototype

String ATTACHMENT

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

Click Source Link

Document

This part should be presented as an attachment.

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()));
    }//from   ww w .j  a va 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.nuxeo.cm.mail.actionpipe.ExtractMessageInformation.java

@SuppressWarnings("unchecked")
protected static void getAttachmentParts(Part p, String defaultFilename, MimetypeRegistry mimeService,
        ExecutionContext context) throws MessagingException, IOException {
    String filename = getFilename(p, defaultFilename);
    List<Blob> blobs = (List<Blob>) context.get(ATTACHMENTS_KEY);

    if (!p.isMimeType("multipart/*")) {
        String disp = p.getDisposition();
        // no disposition => consider it may be body
        if (disp == null && !context.containsKey(BODY_KEY)) {
            // this will need to be parsed
            context.put(BODY_KEY, p.getContent());
        } else if (disp != null
                && (disp.equalsIgnoreCase(Part.ATTACHMENT) || (disp.equalsIgnoreCase(Part.INLINE)
                        && !(p.isMimeType("text/*") || p.isMimeType("image/*"))))) {
            log.debug("Saving attachment to file " + filename);
            Blob blob = Blobs.createBlob(p.getInputStream());
            String mime = DEFAULT_BINARY_MIMETYPE;
            try {
                if (mimeService != null) {
                    ContentType contentType = new ContentType(p.getContentType());
                    mime = mimeService.getMimetypeFromFilenameAndBlobWithDefault(filename, blob,
                            contentType.getBaseType());
                }//  ww w .j av a 2 s  .  co  m
            } catch (MimetypeDetectionException e) {
                log.error(e);
            }
            blob.setMimeType(mime);

            blob.setFilename(filename);

            blobs.add(blob);

            // for debug
            // File f = new File(filename);
            // ((MimeBodyPart) p).saveFile(f);

            log.debug("---------------------------");

        } else {
            log.debug(String.format("Ignoring part with type %s", p.getContentType()));
        }
    }

    if (p.isMimeType("multipart/*")) {
        log.debug("This is a Multipart");
        log.debug("---------------------------");
        Multipart mp = (Multipart) p.getContent();

        int count = mp.getCount();
        for (int i = 0; i < count; i++) {
            getAttachmentParts(mp.getBodyPart(i), defaultFilename, mimeService, context);
        }
    } else if (p.isMimeType(MESSAGE_RFC822_MIMETYPE)) {
        log.debug("This is a Nested Message");
        log.debug("---------------------------");
        getAttachmentParts((Part) p.getContent(), defaultFilename, mimeService, context);
    }

}

From source file:org.simplejavamail.internal.util.MimeMessageParser.java

/**
 * Extracts the content of a MimeMessage recursively.
 *
 * @param part   the current MimePart/* ww w .  j ava 2 s  .  c o m*/
 * @throws MessagingException parsing the MimeMessage failed
 * @throws IOException        parsing the MimeMessage failed
 */
private void parse(final MimePart part) throws MessagingException, IOException {
    extractCustomUserHeaders(part);

    if (isMimeType(part, "text/plain") && plainContent == null
            && !Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
        plainContent = (String) part.getContent();
    } else {
        if (isMimeType(part, "text/html") && htmlContent == null
                && !Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
            htmlContent = (String) part.getContent();
        } else {
            if (isMimeType(part, "multipart/*")) {
                final Multipart mp = (Multipart) part.getContent();
                final int count = mp.getCount();

                // iterate over all MimeBodyPart
                for (int i = 0; i < count; i++) {
                    parse((MimeBodyPart) mp.getBodyPart(i));
                }
            } else {
                final DataSource ds = createDataSource(part);
                // If the diposition is not provided, the part should be treat as attachment
                if (part.getDisposition() == null || Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                    this.attachmentList.put(part.getContentID(), ds);
                } else if (Part.INLINE.equalsIgnoreCase(part.getDisposition())) {
                    this.cidMap.put(part.getContentID(), ds);
                } else {
                    throw new IllegalStateException("invalid attachment type");
                }
            }
        }
    }
}

From source file:com.cubusmail.mail.util.MessageUtils.java

/**
 * Method for checking if the message has attachments.
 *//*from   w w w .j a  v a2 s.c om*/
public static List<MimePart> attachmentsFromPart(Part part) throws MessagingException, IOException {

    List<MimePart> attachmentParts = new ArrayList<MimePart>();
    if (part instanceof MimePart) {
        MimePart mimePart = (MimePart) part;

        if (part.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) mimePart.getContent();
            for (int i = 0; i < mp.getCount(); i++) {
                MimeBodyPart bodyPart = (MimeBodyPart) mp.getBodyPart(i);
                if (Part.ATTACHMENT.equals(bodyPart.getDisposition())
                        || Part.INLINE.equals(bodyPart.getDisposition())) {
                    attachmentParts.add(bodyPart);
                }
            }
        } else if (part.isMimeType("application/*")) {
            attachmentParts.add(mimePart);
        }
    }

    return attachmentParts;
}

From source file:org.jevis.emaildatasource.EMailManager.java

/**
 * Find attachment and save it in inputstream
 *
 * @param message EMail message/*from  w  w w . j  av a2 s.c  o  m*/
 *
 * @return List of InputStream
 */
private static List<InputStream> prepareAnswer(Message message, String filename)
        throws IOException, MessagingException {
    Multipart multiPart = (Multipart) message.getContent();
    List<InputStream> input = new ArrayList<>();
    // For all multipart contents
    for (int i = 0; i < multiPart.getCount(); i++) {

        MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(i);
        String disp = part.getDisposition();
        String partName = part.getFileName();

        Logger.getLogger(EMailDataSource.class.getName()).log(Level.INFO, "is Multipart");
        // If multipart content is attachment
        if (!Part.ATTACHMENT.equalsIgnoreCase(disp) && !StringUtils.isNotBlank(partName)) {
            continue; // dealing with attachments only

        }

        if (Part.ATTACHMENT.equalsIgnoreCase(disp) || disp == null) {
            if (StringUtils.containsIgnoreCase(part.getFileName(), filename)) {
                Logger.getLogger(EMailManager.class.getName()).log(Level.INFO, "Attach found: {0}",
                        part.getFileName());
                final long start = System.currentTimeMillis();
                input.add(toInputStream(part));//add attach to answerlist
                final long answerDone = System.currentTimeMillis();
                Logger.getLogger(EMailDataSource.class.getName()).log(Level.INFO,
                        ">>Attach to inputstream: " + (answerDone - start) + " Millisek.");

            }
        }
    } //for multipart check
    return input;
}

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

/**
 * ??/* ww  w .  j a  v a 2s .  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;
}

From source file:org.silverpeas.util.mail.EMLExtractor.java

private boolean isTextPart(Part part) throws MessagingException {
    String disposition = part.getDisposition();
    if (!Part.ATTACHMENT.equals(disposition) && !Part.INLINE.equals(disposition)) {
        try {/*from ww w .  j av a 2  s  .  co  m*/
            ContentType type = new ContentType(part.getContentType());
            return "text".equalsIgnoreCase(type.getPrimaryType());
        } catch (ParseException e) {
            SilverTrace.error("util", EMLExtractor.class.getSimpleName() + ".getFileName", "root.EX_NO_MESSAGE",
                    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) {
            SilverTrace.error("util", EMLExtractor.class.getSimpleName() + ".getFileName", "root.EX_NO_MESSAGE",
                    e);
        }
    }
    return false;
}

From source file:org.apache.axis2.transport.mail.EMailSender.java

private void createMailMimeMessage(final MimeMessage msg, MailToInfo mailToInfo, OMOutputFormat format)
        throws MessagingException {

    // Create the message part
    BodyPart messageBodyPart = new MimeBase64BodyPart();
    messageBodyPart.setText("");
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    DataSource source = null;//  www. j  a v  a2s  .  co m

    // Part two is attachment
    if (outputStream instanceof ByteArrayOutputStream) {
        source = new ByteArrayDataSource(((ByteArrayOutputStream) outputStream).toByteArray());
    }
    messageBodyPart = new MimeBase64BodyPart();
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setDisposition(Part.ATTACHMENT);

    messageBodyPart.addHeader("Content-Description", "\"" + mailToInfo.getContentDescription() + "\"");

    String contentType = format.getContentType() != null ? format.getContentType()
            : Constants.DEFAULT_CONTENT_TYPE;
    if (contentType.indexOf(SOAP11Constants.SOAP_11_CONTENT_TYPE) > -1) {
        if (messageContext.getSoapAction() != null) {
            messageBodyPart.setHeader(Constants.HEADER_SOAP_ACTION, messageContext.getSoapAction());
        }
    }

    if (contentType.indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) > -1) {
        if (messageContext.getSoapAction() != null) {
            messageBodyPart.setHeader("Content-Type", contentType + "; charset=" + format.getCharSetEncoding()
                    + " ; action=\"" + messageContext.getSoapAction() + "\"");
        }
    } else {
        messageBodyPart.setHeader("Content-Type", contentType + "; charset=" + format.getCharSetEncoding());
    }

    multipart.addBodyPart(messageBodyPart);
    msg.setContent(multipart);

}

From source file:org.silverpeas.core.mail.extractor.EMLExtractor.java

private boolean isTextPart(Part part) throws MessagingException {
    String disposition = part.getDisposition();
    if (!Part.ATTACHMENT.equals(disposition) && !Part.INLINE.equals(disposition)) {
        try {/*from   w  w w . j a v a2s.c  o m*/
            ContentType type = new ContentType(part.getContentType());
            return "text".equalsIgnoreCase(type.getPrimaryType());
        } catch (ParseException e) {
            SilverLogger.getLogger(this).error(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) {
            SilverLogger.getLogger(this).error(e);
        }
    }
    return false;
}

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  av  a  2 s  .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;
}