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:com.cubusmail.mail.util.MessageUtils.java

/**
 * @param part//from w  ww .j  a  v  a  2s.  co  m
 * @return
 * @throws MessagingException
 * @throws IOException
 */
public static boolean hasAttachments(Part part) throws MessagingException, IOException {

    try {
        if (part.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) part.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())) {
                    return true;
                }
            }
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }

    return false;
}

From source file:com.cisco.iwe.services.util.EmailMonitor.java

/**
 * This method returns the corresponding JSON response.'Success = true' in case the Mail contents get stored in the database successfully. 'Success = false' in case of any errors 
 **///from   w w w.  j  a v a  2s  .c o m

public String monitorEmailAndLoadDB() {
    License license = new License();
    license.setLicense(EmailParseConstants.ocrLicenseFile);
    Store emailStore = null;
    Folder folder = null;
    Properties props = new Properties();
    logger.info("EmailMonitor monitorEmailAndLoadDB Enter (+)");
    // Setting session and Store information
    // MailServerConnectivity - get the email credentials based on the environment
    String[] mailCredens = getEmailCredens();
    final String username = mailCredens[0];
    final String password = mailCredens[1];
    logger.info("monitorEmailAndLoadDB : Email ID : " + username);

    try {
        logger.info("EmailMonitor.monitorEmailAndLoadDB get the mail server properties");
        props.put(EmailParseConstants.emailAuthKey, "true");
        props.put(EmailParseConstants.emailHostKey, prop.getProperty(EmailParseConstants.emailHost));
        props.put(EmailParseConstants.emailPortKey, prop.getProperty(EmailParseConstants.emailPort));
        props.put(EmailParseConstants.emailTlsKey, "true");

        logger.info("EmailMonitor.monitorEmailAndLoadDB create the session object with mail server properties");
        Session session = Session.getDefaultInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        // Prod-MailServerConnectivity - create the POP3 store object and
        // connect with the pop server
        logger.info("monitorEmailAndLoadDB : create the POP3 store object");
        emailStore = (Store) session.getStore(prop.getProperty(EmailParseConstants.emailType));
        logger.info("monitorEmailAndLoadDB : Connecting to Store :" + emailStore.toString());
        emailStore.connect(prop.getProperty(EmailParseConstants.emailHost),
                Integer.parseInt(prop.getProperty(EmailParseConstants.emailPort)), username, password);
        logger.info("monitorEmailAndLoadDB : Connection Status:" + emailStore.isConnected());

        // create the folder object
        folder = emailStore.getFolder(prop.getProperty(EmailParseConstants.emailFolder));
        // Check if Inbox exists
        if (!folder.exists()) {
            logger.error("monitorEmailAndLoadDB : No INBOX exists...");
            System.exit(0);
        }
        // Open inbox and read messages
        logger.info("monitorEmailAndLoadDB : Connected to Folder");
        folder.open(Folder.READ_WRITE);

        // retrieve the messages from the folder in an array and process it
        Message[] msgArr = folder.getMessages();
        // Read each message and delete the same once data is stored in DB
        logger.info("monitorEmailAndLoadDB : Message length::::" + msgArr.length);

        SimpleDateFormat sdf2 = new SimpleDateFormat(EmailParseConstants.dateFormat);

        Date sent = null;
        String emailContent = null;
        String contentType = null;
        // for (int i = 0; i < msg.length; i++) {
        for (int i = msgArr.length - 1; i > msgArr.length - 2; i--) {
            Message message = msgArr[i];
            if (!message.isSet(Flags.Flag.SEEN)) {
                try {
                    sent = msgArr[i].getSentDate();
                    contentType = message.getContentType();
                    String fileType = null;
                    byte[] byteArr = null;
                    String validAttachments = EmailParseConstants.validAttachmentTypes;
                    if (contentType.contains("multipart")) {
                        Multipart multiPart = (Multipart) message.getContent();
                        int numberOfParts = multiPart.getCount();
                        for (int partCount = 0; partCount < numberOfParts; partCount++) {
                            MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                            InputStream inStream = (InputStream) part.getInputStream();
                            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                            int nRead;
                            byte[] data = new byte[16384];
                            while ((nRead = inStream.read(data, 0, data.length)) != -1) {
                                buffer.write(data, 0, nRead);
                            }
                            buffer.flush();
                            byteArr = buffer.toByteArray();
                            if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                                fileType = part.getFileName().substring(part.getFileName().lastIndexOf("."),
                                        part.getFileName().length());
                                String fileDir = part.getFileName();
                                if (validAttachments.contains(fileType)) {
                                    part.saveFile(fileDir);
                                    saveAttachmentAndText(message.getFrom()[0].toString(), message.getSubject(),
                                            byteArr, emailContent.getBytes(), fileType, sent,
                                            fileType.equalsIgnoreCase(".PDF") ? scanPDF(fileDir)
                                                    : scanImage(fileDir).toString());
                                    deleteFile(fileDir);
                                } else {
                                    sendNotification();
                                }

                            } else {
                                // this part may be the message content
                                emailContent = part.getContent().toString();
                            }
                        }
                    } else if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                        Object content = message.getContent();
                        if (content != null) {
                            emailContent = content.toString();
                        }
                    }
                    message.setFlag(Flags.Flag.DELETED, false);
                    logger.info(
                            "monitorEmailAndLoadDB : loadSuccess : Mail Parsed for : " + message.getSubject());
                    logger.info("monitorEmailAndLoadDB : loadSuccess : Created at : " + sdf2.format(sent));
                    logger.info("Message deleted");
                } catch (IOException e) {
                    logger.error("IO Exception in email monitoring: " + e);
                    logger.error(
                            "IO Exception in email monitoring message: " + Arrays.toString(e.getStackTrace()));
                } catch (SQLException sexp) {
                    logger.error("SQLException Occurred GetSpogDetails-db2 :", sexp);
                    buildErrorJson(ExceptionConstants.sqlErrCode, ExceptionConstants.sqlErrMsg);
                } catch (Exception e) {
                    logger.error("Unknown Exception in email monitoring: " + e);
                    logger.error("Unknown Exception in email monitoring message: "
                            + Arrays.toString(e.getStackTrace()));
                }
            }
        }

        // Close folder and store
        folder.close(true);
        emailStore.close();

    } catch (NoSuchProviderException e) {
        logger.error("monitorEmailAndLoadDB : NoSuchProviderException in email monitoring: " + e);
        logger.error("monitorEmailAndLoadDB : NoSuchProviderException in email monitoring message: "
                + Arrays.toString(e.getStackTrace()));
    } catch (MessagingException e) {
        logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + e);
        logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring message: "
                + Arrays.toString(e.getStackTrace()));
    } finally {
        if (folder != null && folder.isOpen()) {
            // Close folder and store
            try {
                folder.close(true);
                emailStore.close();
            } catch (MessagingException e) {
                logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + e);
                logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: "
                        + Arrays.toString(e.getStackTrace()));
            }
        }
    }
    logger.info("EmailMonitor monitorEmailAndLoadDB Exit (-)");
    return buildSuccessJson().toString();
}

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

public MimeMessageHelper addAttachment(String name, String type, byte[] content) throws MessagingException {

    BodyPart attachmentPart = new MimeBodyPart();
    ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(content, type);

    attachmentPart.setDataHandler(new DataHandler(byteArrayDataSource));
    attachmentPart.setFileName(name);//  w ww.  j  av a2s .c om

    attachmentPart.setDisposition(Part.ATTACHMENT);
    attachments.add(attachmentPart);
    return this;
}

From source file:org.apache.hupa.server.handler.AbstractFetchMessagesHandler.java

private boolean hasAttachment(Message message) throws MessagingException {
    if (message.getContentType().startsWith("multipart/")) {
        try {/*from  ww  w  .  j a  v  a2s .co  m*/
            Object content;

            content = message.getContent();

            if (content instanceof Multipart) {
                Multipart mp = (Multipart) content;
                if (mp.getCount() > 1) {
                    for (int i = 0; i < mp.getCount(); i++) {
                        String disp = mp.getBodyPart(i).getDisposition();
                        if (disp != null && disp.equalsIgnoreCase(Part.ATTACHMENT)) {
                            return true;
                        }
                    }
                }

            }
        } catch (IOException e) {
            logger.error("Error while get content of message " + message.getMessageNumber());
        }

    }
    return false;
}

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

private void validateAttachmentBodyPart(BodyPart bodyPart) throws NotificationValidationException {
    try {/*from w  ww . j  a v a2  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.solr.handler.dataimport.FsMailEntityProcessor.java

public boolean addPartToDocument(Part part, Map<String, Object> row, boolean outerMost) throws Exception {
    if (outerMost && part instanceof Message) {
        if (!addEnvelopToDocument(part, row)) {
            return false;
        }/*from  ww w .  j  a  va 2s.  c o m*/
        // store hash
        row.put(HASH, DigestUtils.md5Hex((String) row.get(FROM_CLEAN) + "" + (String) row.get(SUBJECT)));
    }

    String ct = part.getContentType();
    ContentType ctype = new ContentType(ct);
    if (part.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) part.getContent();
        int count = mp.getCount();
        if (part.isMimeType("multipart/alternative")) {
            count = 1;
        }
        for (int i = 0; i < count; i++) {
            addPartToDocument(mp.getBodyPart(i), row, false);
        }
    } else if (part.isMimeType("message/rfc822")) {
        addPartToDocument((Part) part.getContent(), row, false);
    } else {
        String disp = part.getDisposition();
        @SuppressWarnings("resource") // Tika will close stream
        InputStream is = part.getInputStream();
        String fileName = part.getFileName();
        Metadata md = new Metadata();
        md.set(HttpHeaders.CONTENT_TYPE, ctype.getBaseType().toLowerCase(Locale.ROOT));
        md.set(TikaMetadataKeys.RESOURCE_NAME_KEY, fileName);
        String content = this.tika.parseToString(is, md);
        if (disp != null && disp.equalsIgnoreCase(Part.ATTACHMENT)) {
            if (row.get(ATTACHMENT) == null) {
                row.put(ATTACHMENT, new ArrayList<String>());
            }
            List<String> contents = (List<String>) row.get(ATTACHMENT);
            contents.add(content);
            row.put(ATTACHMENT, contents);
            if (row.get(ATTACHMENT_NAMES) == null) {
                row.put(ATTACHMENT_NAMES, new ArrayList<String>());
            }
            List<String> names = (List<String>) row.get(ATTACHMENT_NAMES);
            names.add(fileName);
            row.put(ATTACHMENT_NAMES, names);
        } else {
            if (row.get(CONTENT) == null) {
                row.put(CONTENT, new ArrayList<String>());
            }
            List<String> contents = (List<String>) row.get(CONTENT);
            contents.add(content);
            row.put(CONTENT, contents);
        }
    }
    return true;
}

From source file:com.szmslab.quickjavamail.receive.MessageLoader.java

/**
 * ?????MessageContent????/*from   w  ww . java  2 s.  co  m*/
 *
 * @param multiPart
 *            ?
 * @param msgContent
 *            ????
 * @throws MessagingException
 * @throws IOException
 */
private void setMultipartContent(Multipart multiPart, MessageContent msgContent)
        throws MessagingException, IOException {
    for (int i = 0; i < multiPart.getCount(); i++) {
        Part part = multiPart.getBodyPart(i);
        if (part.getContentType().indexOf("multipart") >= 0) {
            setMultipartContent((Multipart) part.getContent(), msgContent);
        } else {
            String disposition = part.getDisposition();
            if (Part.ATTACHMENT.equals(disposition)) {
                // Disposition?"attachment"???ContentType????
                msgContent.attachmentFileList.add(new AttachmentFile(MimeUtility.decodeText(part.getFileName()),
                        part.getDataHandler().getDataSource()));
            } else {
                if (part.isMimeType("text/html")) {
                    msgContent.html = part.getContent().toString();
                } else if (part.isMimeType("text/plain")) {
                    msgContent.text = part.getContent().toString();
                } else {
                    // Disposition?"inline"???ContentType??
                    if (Part.INLINE.equals(disposition)) {
                        String cid = "";
                        if (part instanceof MimeBodyPart) {
                            MimeBodyPart mimePart = (MimeBodyPart) part;
                            cid = mimePart.getContentID();
                        }
                        msgContent.inlineImageFileList
                                .add(new InlineImageFile(cid, MimeUtility.decodeText(part.getFileName()),
                                        part.getDataHandler().getDataSource()));
                    }
                }
            }
        }
    }
}

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

/**
 * ?/*from w ww.ja v a 2  s . com*/
 * 
 * @param part
 * @throws MessagingException
 * @throws IOException
 */
public void parseAttachment(Part part) throws MessagingException, IOException {
    String filename = "";
    if (part.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) part.getContent();
        for (int i = 0; i < mp.getCount(); i++) {
            BodyPart mpart = mp.getBodyPart(i);
            String dispostion = mpart.getDisposition();
            if ((dispostion != null)
                    && (dispostion.equals(Part.ATTACHMENT) || dispostion.equals(Part.INLINE))) {
                filename = mpart.getFileName();
                if (filename != null) {
                    logger.debug("orig filename=" + filename);
                    if (filename.indexOf("?") != -1) {
                        filename = new String(filename.getBytes("GBK"), "UTF-8");
                    }
                    if (filename.toLowerCase().indexOf("gb2312") != -1) {
                        filename = MimeUtility.decodeText(filename);
                    }
                    filename = MailUtils.convertString(filename);
                    logger.debug("filename=" + filename);
                    parseFileContent(filename, mpart.getInputStream());
                }
            } else if (mpart.isMimeType("multipart/*")) {
                parseAttachment(mpart);
            } else {
                filename = mpart.getFileName();
                if (filename != null) {
                    logger.debug("orig filename=" + filename);
                    if (filename.indexOf("?") != -1) {
                        filename = new String(filename.getBytes("GBK"), "UTF-8");
                    }
                    if (filename.toLowerCase().indexOf("gb2312") != -1) {
                        filename = MimeUtility.decodeText(filename);
                    }
                    filename = MailUtils.convertString(filename);
                    parseFileContent(filename, mpart.getInputStream());
                    logger.debug("filename=" + filename);
                }
            }
        }

    } else if (part.isMimeType("message/rfc822")) {
        parseAttachment((Part) part.getContent());
    }
}

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 va 2  s .com*/
 * 
 * @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:org.silverpeas.components.mailinglist.service.job.MailProcessor.java

/**
 * Analyze the part to check if it is an attachment, a base64 encoded file or some text.
 * @param part the part to be analyzed.//from  w  w  w.j a  v a  2 s  .  c o m
 * @return true if it is some text - false otherwise.
 * @throws MessagingException
 */
protected boolean isTextPart(Part part) throws MessagingException {
    String disposition = part.getDisposition();
    if (!Part.ATTACHMENT.equals(disposition) && !Part.INLINE.equals(disposition)) {
        try {
            ContentType type = new ContentType(part.getContentType());
            return "text".equalsIgnoreCase(type.getPrimaryType());
        } catch (ParseException e) {
            logger.error(e.getMessage(), 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) {
            logger.error(e.getMessage(), e);
        }
    }
    return false;
}