Example usage for javax.mail Message getContentType

List of usage examples for javax.mail Message getContentType

Introduction

In this page you can find the example usage for javax.mail Message getContentType.

Prototype

public String getContentType() throws MessagingException;

Source Link

Document

Returns the Content-Type of the content of this part.

Usage

From source file:nz.net.orcon.kanban.automation.actions.EmailReceiverAction.java

public void downloadEmails(String mailStoreProtocol, String mailStoreHost, String mailStoreUserName,
        String mailStorePassword) throws IOException {

    Session session = getMailStoreSession(mailStoreProtocol, mailStoreHost, mailStoreUserName,
            mailStorePassword);/*from  w ww .j  ava 2  s  .c  o  m*/
    try {
        // connects to the message store
        Store store = session.getStore(mailStoreProtocol);
        store.connect(mailStoreHost, mailStoreUserName, mailStorePassword);

        logger.info("connected to message store");

        // opens the inbox folder
        Folder folderInbox = store.getFolder("INBOX");
        folderInbox.open(Folder.READ_ONLY);

        // fetches new messages from server
        Message[] messages = folderInbox.getMessages();

        for (int i = 0; i < messages.length; i++) {
            Message msg = messages[i];
            Address[] fromAddress = msg.getFrom();
            String from = fromAddress[0].toString();
            String subject = msg.getSubject();
            String toList = parseAddresses(msg.getRecipients(RecipientType.TO));
            String ccList = parseAddresses(msg.getRecipients(RecipientType.CC));
            String sentDate = msg.getSentDate().toString();

            String contentType = msg.getContentType();
            String messageContent = "";

            if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                try {
                    Object content = msg.getContent();
                    if (content != null) {
                        messageContent = content.toString();
                    }
                } catch (Exception ex) {
                    messageContent = "[Error downloading content]";
                    ex.printStackTrace();
                }
            }

            // print out details of each message
            System.out.println("Message #" + (i + 1) + ":");
            System.out.println("\t From: " + from);
            System.out.println("\t To: " + toList);
            System.out.println("\t CC: " + ccList);
            System.out.println("\t Subject: " + subject);
            System.out.println("\t Sent Date: " + sentDate);
            System.out.println("\t Message: " + messageContent);
        }

        // disconnect
        folderInbox.close(false);
        store.close();
    } catch (NoSuchProviderException ex) {
        logger.warn("No provider for protocol: " + mailStoreProtocol + " " + ex);
    } catch (MessagingException ex) {
        logger.error("Could not connect to the message store" + ex);
    }
}

From source file:org.mule.transport.email.MailMuleMessageFactory.java

@Override
protected void addProperties(DefaultMuleMessage muleMessage, Object transportMessage) throws Exception {
    super.addProperties(muleMessage, transportMessage);

    Message mailMessage = (Message) transportMessage;

    addRecipientProperty(muleMessage, mailMessage, RecipientType.TO, MailProperties.TO_ADDRESSES_PROPERTY);
    addRecipientProperty(muleMessage, mailMessage, RecipientType.CC, MailProperties.CC_ADDRESSES_PROPERTY);
    addRecipientProperty(muleMessage, mailMessage, RecipientType.BCC, MailProperties.BCC_ADDRESSES_PROPERTY);

    addReplyToProperty(muleMessage, mailMessage);
    addFromProperty(muleMessage, mailMessage);

    muleMessage.setInboundProperty(MailProperties.SUBJECT_PROPERTY,
            StringUtils.defaultIfEmpty(mailMessage.getSubject(), "(no subject)"));
    muleMessage.setInboundProperty(MailProperties.CONTENT_TYPE_PROPERTY,
            StringUtils.defaultIfEmpty(mailMessage.getContentType(), "text/plain"));

    addSentDateProperty(muleMessage, mailMessage);
    addMailHeadersToMessageProperties(mailMessage, muleMessage);
}

From source file:org.apache.camel.component.mail.MailBinding.java

/**
 * Extracts the body from the Mail message
 *//*www  .ja  v a  2 s  . c o m*/
public Object extractBodyFromMail(Exchange exchange, MailMessage mailMessage) {
    Message message = mailMessage.getMessage();
    try {
        return message.getContent();
    } catch (Exception e) {
        // try to fix message in case it has an unsupported encoding in the Content-Type header
        UnsupportedEncodingException uee = ObjectHelper.getException(UnsupportedEncodingException.class, e);
        if (uee != null) {
            LOG.debug("Unsupported encoding detected: " + uee.getMessage());
            try {
                String contentType = message.getContentType();
                String type = ObjectHelper.before(contentType, "charset=");
                if (type != null) {
                    // try again with fixed content type
                    LOG.debug("Trying to extract mail message again with fixed Content-Type: " + type);
                    // Since message is read-only, we need to use a copy
                    MimeMessage messageCopy = new MimeMessage((MimeMessage) message);
                    messageCopy.setHeader("Content-Type", type);
                    Object body = messageCopy.getContent();
                    // If we got this far, our fix worked...
                    // Replace the MailMessage's Message with the copy
                    mailMessage.setMessage(messageCopy);
                    return body;
                }
            } catch (Exception e2) {
                // fall through and let original exception be thrown
            }
        }

        throw new RuntimeCamelException("Failed to extract body due to: " + e.getMessage() + ". Exchange: "
                + exchange + ". Message: " + message, e);
    }
}

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

public static IndexableMailMessage fromJavaMailMessage(final Message jmm, final boolean withTextContent,
        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()));
    }/*ww w . j a v a2 s. c om*/

    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);

        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 (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:net.fenyo.mail4hotspot.service.MailManager.java

public String getMessageContentString(final Message message) throws IOException, MessagingException {
    final Object content = message.getContent();
    if (String.class.isInstance(content))
        // content-type: text/{plain, html, etc.}
        // prfrer isMimeType(...)  getContentType().equals(...) car getContentType() peut contenir aussi le charset et renvoyer une string comme suit : << text/html; charset="us-ascii" >>
        if (message.isMimeType("text/html"))
            return GenericTools.html2Text((String) content);
        else if (message.isMimeType("text/plain"))
            return (String) content;
        else {/*from  w  ww.  j  a v a 2s  .com*/
            log.warn("message content-type not handled: " + message.getContentType()
                    + " -> downgrading to String");
            return (String) content;
        }
    else if (MimeMultipart.class.isInstance(content)) {
        boolean mixed = false;
        if (message.isMimeType("multipart/mixed"))
            mixed = true;
        else if (message.isMimeType("multipart/alternative"))
            mixed = false;
        else {
            log.warn("multipart content-type not handled: " + message.getContentType()
                    + " -> downgrading to multipart/mixed");
            mixed = true;
        }
        return getMultipartContentString((MimeMultipart) content, mixed);
    } else {
        log.warn("invalid message content type and class: " + content.getClass().toString() + " - "
                + message.getContentType());
        return "";
    }
}

From source file:org.apache.jmeter.protocol.mail.sampler.MailReaderSampler.java

/**
 * {@inheritDoc}/*from   w ww.  jav a 2  s . c  om*/
 */
@Override
public SampleResult sample(Entry e) {
    SampleResult parent = new SampleResult();
    boolean isOK = false; // Did sample succeed?
    final boolean deleteMessages = getDeleteMessages();
    final String serverProtocol = getServerType();

    parent.setSampleLabel(getName());

    String samplerString = toString();
    parent.setSamplerData(samplerString);

    /*
     * Perform the sampling
     */
    parent.sampleStart(); // Start timing
    try {
        // Create empty properties
        Properties props = new Properties();

        if (isUseStartTLS()) {
            props.setProperty(mailProp(serverProtocol, "starttls.enable"), TRUE); // $NON-NLS-1$
            if (isEnforceStartTLS()) {
                // Requires JavaMail 1.4.2+
                props.setProperty(mailProp(serverProtocol, "starttls.require"), TRUE); // $NON-NLS-1$
            }
        }

        if (isTrustAllCerts()) {
            if (isUseSSL()) {
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"),
                        TRUST_ALL_SOCKET_FACTORY); // $NON-NLS-1$
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            } else if (isUseStartTLS()) {
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"),
                        TRUST_ALL_SOCKET_FACTORY); // $NON-NLS-1$
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            }
        } else if (isUseLocalTrustStore()) {
            File truststore = new File(getTrustStoreToUse());
            log.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath());
            if (!truststore.exists()) {
                log.info("load local truststore -Failed to load truststore from: "
                        + truststore.getAbsolutePath());
                truststore = new File(FileServer.getFileServer().getBaseDir(), getTrustStoreToUse());
                log.info("load local truststore -Attempting to read truststore from:  "
                        + truststore.getAbsolutePath());
                if (!truststore.exists()) {
                    log.info("load local truststore -Failed to load truststore from: "
                            + truststore.getAbsolutePath()
                            + ". Local truststore not available, aborting execution.");
                    throw new IOException("Local truststore file not found. Also not available under : "
                            + truststore.getAbsolutePath());
                }
            }
            if (isUseSSL()) {
                // Requires JavaMail 1.4.2+
                props.put(mailProp(serverProtocol, "ssl.socketFactory"), // $NON-NLS-1$ 
                        new LocalTrustStoreSSLSocketFactory(truststore));
                props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            } else if (isUseStartTLS()) {
                // Requires JavaMail 1.4.2+
                props.put(mailProp(serverProtocol, "ssl.socketFactory"), // $NON-NLS-1$
                        new LocalTrustStoreSSLSocketFactory(truststore));
                props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            }
        }

        // Get session
        Session session = Session.getInstance(props, null);

        // Get the store
        Store store = session.getStore(serverProtocol);
        store.connect(getServer(), getPortAsInt(), getUserName(), getPassword());

        // Get folder
        Folder folder = store.getFolder(getFolder());
        if (deleteMessages) {
            folder.open(Folder.READ_WRITE);
        } else {
            folder.open(Folder.READ_ONLY);
        }

        final int messageTotal = folder.getMessageCount();
        int n = getNumMessages();
        if (n == ALL_MESSAGES || n > messageTotal) {
            n = messageTotal;
        }

        // Get directory
        Message[] messages = folder.getMessages(1, n);
        StringBuilder pdata = new StringBuilder();
        pdata.append(messages.length);
        pdata.append(" messages found\n");
        parent.setResponseData(pdata.toString(), null);
        parent.setDataType(SampleResult.TEXT);
        parent.setContentType("text/plain"); // $NON-NLS-1$

        final boolean headerOnly = getHeaderOnly();
        busy = true;
        for (Message message : messages) {
            StringBuilder cdata = new StringBuilder();
            SampleResult child = new SampleResult();
            child.sampleStart();

            cdata.append("Message "); // $NON-NLS-1$
            cdata.append(message.getMessageNumber());
            child.setSampleLabel(cdata.toString());
            child.setSamplerData(cdata.toString());
            cdata.setLength(0);

            final String contentType = message.getContentType();
            child.setContentType(contentType);// Store the content-type
            child.setDataEncoding(RFC_822_DEFAULT_ENCODING); // RFC 822 uses ascii per default
            child.setEncodingAndType(contentType);// Parse the content-type

            if (isStoreMimeMessage()) {
                // Don't save headers - they are already in the raw message
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                message.writeTo(bout);
                child.setResponseData(bout.toByteArray()); // Save raw message
                child.setDataType(SampleResult.TEXT);
            } else {
                @SuppressWarnings("unchecked") // Javadoc for the API says this is OK
                Enumeration<Header> hdrs = message.getAllHeaders();
                while (hdrs.hasMoreElements()) {
                    Header hdr = hdrs.nextElement();
                    String value = hdr.getValue();
                    try {
                        value = MimeUtility.decodeText(value);
                    } catch (UnsupportedEncodingException uce) {
                        // ignored
                    }
                    cdata.append(hdr.getName()).append(": ").append(value).append("\n");
                }
                child.setResponseHeaders(cdata.toString());
                cdata.setLength(0);
                if (!headerOnly) {
                    appendMessageData(child, message);
                }
            }

            if (deleteMessages) {
                message.setFlag(Flags.Flag.DELETED, true);
            }
            child.setResponseOK();
            if (child.getEndTime() == 0) {// Avoid double-call if addSubResult was called.
                child.sampleEnd();
            }
            parent.addSubResult(child);
        }

        // Close connection
        folder.close(true);
        store.close();

        parent.setResponseCodeOK();
        parent.setResponseMessageOK();
        isOK = true;
    } catch (NoClassDefFoundError | IOException ex) {
        log.debug("", ex);// No need to log normally, as we set the status
        parent.setResponseCode("500"); // $NON-NLS-1$
        parent.setResponseMessage(ex.toString());
    } catch (MessagingException ex) {
        log.debug("", ex);// No need to log normally, as we set the status
        parent.setResponseCode("500"); // $NON-NLS-1$
        parent.setResponseMessage(ex.toString() + "\n" + samplerString); // $NON-NLS-1$
    } finally {
        busy = false;
    }

    if (parent.getEndTime() == 0) {// not been set by any child samples
        parent.sampleEnd();
    }
    parent.setSuccessful(isOK);
    return parent;
}

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  w w w .  ja v  a  2  s.co  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:com.aquest.emailmarketing.web.service.BouncedEmailService.java

/**
 * Process bounces.//  ww  w. j  a  v a  2 s.  c  o m
 *
 * @param protocol the protocol
 * @param host the host
 * @param port the port
 * @param userName the user name
 * @param password the password
 */
public void processBounces(String protocol, String host, String port, String userName, String password) {
    Properties properties = getServerProperties(protocol, host, port);
    Session session = Session.getDefaultInstance(properties);

    List<BounceCode> bounceCodes = bounceCodeService.getAllBounceCodes();

    try {
        // connects to the message store
        Store store = session.getStore(protocol);
        System.out.println(userName);
        System.out.println(password);
        System.out.println(userName.length());
        System.out.println(password.length());
        //store.connect(userName, password);
        //TODO: ispraviti username i password da idu iz poziva a ne hardcoded
        store.connect("bojan.dimic@aquest-solutions.com", "bg181076");

        // opens the inbox folder
        Folder folderInbox = store.getFolder("INBOX");
        folderInbox.open(Folder.READ_ONLY);

        // fetches new messages from server
        Message[] messages = folderInbox.getMessages();

        for (int i = 0; i < messages.length; i++) {
            BouncedEmail bouncedEmail = new BouncedEmail();
            Message msg = messages[i];
            Address[] fromAddress = msg.getFrom();
            String from = fromAddress[0].toString();
            String failedAddress = "";
            Enumeration<?> headers = messages[i].getAllHeaders();
            while (headers.hasMoreElements()) {
                Header h = (Header) headers.nextElement();
                //System.out.println(h.getName() + ":" + h.getValue());
                //System.out.println("");                
                String mID = h.getName();
                if (mID.contains("X-Failed-Recipients")) {
                    failedAddress = h.getValue();
                }
            }
            String subject = msg.getSubject();
            String toList = parseAddresses(msg.getRecipients(RecipientType.TO));
            String ccList = parseAddresses(msg.getRecipients(RecipientType.CC));
            String sentDate = msg.getSentDate().toString();

            String contentType = msg.getContentType();
            String messageContent = "";

            if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                try {
                    Object content = msg.getContent();
                    if (content != null) {
                        messageContent = content.toString();
                    }
                } catch (Exception ex) {
                    messageContent = "[Error downloading content]";
                    ex.printStackTrace();
                }
            }

            String bounceReason = "Unknown reason";

            for (BounceCode bounceCode : bounceCodes) {
                if (messageContent.contains(bounceCode.getCode())) {
                    bounceReason = bounceCode.getExplanation();
                }
            }

            //                if(messageContent.contains(" 550 ") || messageContent.contains(" 550-")) {bounceReason="Users mailbox was unavailable (such as not found)";}
            //                if(messageContent.contains(" 554 ") || messageContent.contains(" 554-")) {bounceReason="The transaction failed for some unstated reason.";}
            //                
            //                // enhanced bounce codes
            //                if(messageContent.contains("5.0.0")) {bounceReason="Unknown issue";}
            //                if(messageContent.contains("5.1.0")) {bounceReason="Other address status";}
            //                if(messageContent.contains("5.1.1")) {bounceReason="Bad destination mailbox address";}
            //                if(messageContent.contains("5.1.2")) {bounceReason="Bad destination system address";}
            //                if(messageContent.contains("5.1.3")) {bounceReason="Bad destination mailbox address syntax";}
            //                if(messageContent.contains("5.1.4")) {bounceReason="Destination mailbox address ambiguous";}
            //                if(messageContent.contains("5.1.5")) {bounceReason="Destination mailbox address valid";}
            //                if(messageContent.contains("5.1.6")) {bounceReason="Mailbox has moved";}
            //                if(messageContent.contains("5.7.1")) {bounceReason="Delivery not authorized, message refused";}

            // print out details of each message
            System.out.println("Message #" + (i + 1) + ":");
            System.out.println("\t From: " + from);
            System.out.println("\t To: " + toList);
            System.out.println("\t CC: " + ccList);
            System.out.println("\t Subject: " + subject);
            System.out.println("\t Sent Date: " + sentDate);
            System.out.println("\t X-Failed-Recipients:" + failedAddress);
            System.out.println("\t Content Type:" + contentType);
            System.out.println("\t Bounce reason:" + bounceReason);
            //System.out.println("\t Message: " + messageContent);

            bouncedEmail.setEmail_address(failedAddress);
            bouncedEmail.setBounce_reason(bounceReason);

            //Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
            SimpleDateFormat sqlFormat = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH);
            //String strDate = date.toString();
            System.out.println(sentDate);
            Date dt = null;
            //Date nd = null;
            try {
                dt = formatter.parse(sentDate);
                //nd = sqlFormat.parse(dt.toString());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            System.out.println("Date " + dt.toString());
            //System.out.println("Date " + nd.toString());
            System.out.println(new Timestamp(new Date().getTime()));
            bouncedEmail.setSend_date(dt);
            bouncedEmailDao.saveOrUpdate(bouncedEmail);
        }

        // disconnect
        folderInbox.close(false);
        store.close();
    } catch (NoSuchProviderException ex) {
        System.out.println("No provider for protocol: " + protocol);
        ex.printStackTrace();
    } catch (MessagingException ex) {
        System.out.println("Could not connect to the message store");
        ex.printStackTrace();
    }
}

From source file:org.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java

private EmailMessage wrapMessage(Message msg, boolean populateContent, Session session)
        throws MessagingException, IOException, ScanException, PolicyException {

    // Prepare subject
    String subject = msg.getSubject();
    if (!StringUtils.isBlank(subject)) {
        AntiSamy as = new AntiSamy();
        CleanResults cr = as.scan(subject, policy);
        subject = cr.getCleanHTML();/* w  w  w . j  a va 2 s . co  m*/
    }

    // Prepare content if requested
    EmailMessageContent msgContent = null; // default...
    if (populateContent) {
        // Defend against the dreaded: "Unable to load BODYSTRUCTURE"
        try {
            msgContent = getMessageContent(msg.getContent(), msg.getContentType());
        } catch (MessagingException me) {
            // We are unable to read digitally-signed messages (perhaps
            // others?) in the API-standard way;  we have to use a work around.
            // See: http://www.oracle.com/technetwork/java/faq-135477.html#imapserverbug
            // Logging as DEBUG because this behavior is known & expected.
            log.debug("Difficulty reading a message (digitally signed?). Attempting workaround...");
            try {
                MimeMessage mm = (MimeMessage) msg;
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                mm.writeTo(bos);
                bos.close();
                SharedByteArrayInputStream bis = new SharedByteArrayInputStream(bos.toByteArray());
                MimeMessage copy = new MimeMessage(session, bis);
                bis.close();
                msgContent = getMessageContent(copy.getContent(), copy.getContentType());
            } catch (Throwable t) {
                log.error("Failed to read message body", t);
                msgContent = new EmailMessageContent("UNABLE TO READ MESSAGE BODY: " + t.getMessage(), false);
            }
        }

        // Sanitize with AntiSamy
        String content = msgContent.getContentString();
        if (!StringUtils.isBlank(content)) {
            AntiSamy as = new AntiSamy();
            CleanResults cr = as.scan(content, policy);
            content = cr.getCleanHTML();
        }
        msgContent.setContentString(content);
    }

    int messageNumber = msg.getMessageNumber();

    // Prepare the UID if present
    String uid = null; // default
    if (msg.getFolder() instanceof UIDFolder) {
        uid = Long.toString(((UIDFolder) msg.getFolder()).getUID(msg));
    }

    Address[] addr = msg.getFrom();
    String sender = getFormattedAddresses(addr);
    Date sentDate = msg.getSentDate();

    boolean unread = !msg.isSet(Flag.SEEN);
    boolean answered = msg.isSet(Flag.ANSWERED);
    boolean deleted = msg.isSet(Flag.DELETED);
    // Defend against the dreaded: "Unable to load BODYSTRUCTURE"
    boolean multipart = false; // sensible default;
    String contentType = null; // sensible default
    try {
        multipart = msg.getContentType().toLowerCase().startsWith(CONTENT_TYPE_ATTACHMENTS_PATTERN);
        contentType = msg.getContentType();
    } catch (MessagingException me) {
        // Message was digitally signed and we are unable to read it;
        // logging as DEBUG because this issue is known/expected, and
        // because the user's experience is in no way affected (at this point)
        log.debug("Message content unavailable (digitally signed?);  "
                + "message will appear in the preview table correctly, " + "but the body will not be viewable");
        log.trace(me.getMessage(), me);
    }
    String to = getTo(msg);
    String cc = getCc(msg);
    String bcc = getBcc(msg);
    return new EmailMessage(messageNumber, uid, sender, subject, sentDate, unread, answered, deleted, multipart,
            contentType, msgContent, to, cc, bcc);
}

From source file:com.liferay.mail.imap.IMAPAccessor.java

public void storeEnvelopes(long folderId, Folder jxFolder, Message[] jxMessages) throws PortalException {

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();//from  w ww.j  a va2s .  co  m

    try {
        FetchProfile fetchProfile = new FetchProfile();

        fetchProfile.add(UIDFolder.FetchProfileItem.ENVELOPE);
        fetchProfile.add(UIDFolder.FetchProfileItem.FLAGS);
        fetchProfile.add(UIDFolder.FetchProfileItem.UID);

        jxFolder.fetch(jxMessages, fetchProfile);

        for (Message jxMessage : jxMessages) {
            String sender = InternetAddressUtil.toString(jxMessage.getFrom());
            String to = InternetAddressUtil.toString(jxMessage.getRecipients(RecipientType.TO));
            String cc = InternetAddressUtil.toString(jxMessage.getRecipients(RecipientType.CC));
            String bcc = InternetAddressUtil.toString(jxMessage.getRecipients(RecipientType.BCC));
            Date sentDate = jxMessage.getSentDate();
            String subject = jxMessage.getSubject();
            String flags = getFlags(jxMessage);
            long remoteMessageId = getUID(jxFolder, jxMessage);
            String contentType = jxMessage.getContentType();

            try {
                MessageLocalServiceUtil.getMessage(folderId, remoteMessageId);
            } catch (NoSuchMessageException nsme) {
                MessageLocalServiceUtil.addMessage(_user.getUserId(), folderId, sender, to, cc, bcc, sentDate,
                        subject, StringPool.BLANK, flags, remoteMessageId, contentType);
            }
        }

        com.liferay.mail.model.Folder folder = FolderLocalServiceUtil.getFolder(folderId);

        FolderLocalServiceUtil.updateFolder(folderId, folder.getFullName(), folder.getDisplayName(),
                jxFolder.getMessageCount());
    } catch (MessagingException me) {
        throw new MailException(me);
    }

    if (_log.isDebugEnabled()) {
        stopWatch.stop();

        _log.debug("Downloaded " + jxMessages.length + " messages from folder " + jxFolder.getFullName()
                + " completed in " + stopWatch.getTime() + " ms");
    }
}