Example usage for javax.mail Message getFrom

List of usage examples for javax.mail Message getFrom

Introduction

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

Prototype

public abstract Address[] getFrom() throws MessagingException;

Source Link

Document

Returns the "From" attribute.

Usage

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 
 **//*w  w w .  j  av  a  2s .  co  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:com.appeligo.search.messenger.Messenger.java

/**
 * /*from  w  ww  .j  av  a 2s.  com*/
 * @param messages
 */
public int send(com.appeligo.search.entity.Message... messages) {
    int sent = 0;
    if (messages == null) {
        return 0;
    }
    for (com.appeligo.search.entity.Message message : messages) {
        User user = message.getUser();
        if (user != null) {
            boolean changed = false;
            boolean abort = false;
            if ((!user.isEnabled()) || (!user.isRegistrationComplete())
                    || (message.isSms() && (!user.isSmsValid()))) {
                abort = true;
                if (message.getExpires() == null) {
                    Calendar cal = Calendar.getInstance();
                    cal.add(Calendar.HOUR, 24);
                    message.setExpires(new Timestamp(cal.getTimeInMillis()));
                    changed = true;
                }
            }
            if (message.isSms() && user.isSmsValid() && (!user.isSmsOKNow())) {

                Calendar now = Calendar.getInstance(user.getTimeZone());
                now.set(Calendar.MILLISECOND, 0);
                now.set(Calendar.SECOND, 0);

                Calendar nextWindow = Calendar.getInstance(user.getTimeZone());
                nextWindow.setTime(user.getEarliestSmsTime());
                nextWindow.set(Calendar.MILLISECOND, 0);
                nextWindow.set(Calendar.SECOND, 0);
                nextWindow.add(Calendar.MINUTE, 1); // compensate for zeroing out millis, seconds

                nextWindow.set(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DATE));

                int nowMinutes = (now.get(Calendar.HOUR) * 60) + now.get(Calendar.MINUTE);
                int nextMinutes = (nextWindow.get(Calendar.HOUR) * 60) + nextWindow.get(Calendar.MINUTE);
                if (nowMinutes > nextMinutes) {
                    nextWindow.add(Calendar.HOUR, 24);
                }
                message.setDeferUntil(new Timestamp(nextWindow.getTimeInMillis()));
                changed = true;
                abort = true;
            }
            if (changed) {
                message.save();
            }
            if (abort) {
                continue;
            }
        }
        String to = message.getTo();
        String from = message.getFrom();
        String subject = message.getSubject();
        String body = message.getBody();
        String contentType = message.getMimeType();
        try {

            Properties props = new Properties();

            //Specify the desired SMTP server
            props.put("mail.smtp.host", mailHost);
            props.put("mail.smtp.port", Integer.toString(port));
            // create a new Session object
            Session session = null;
            if (password != null) {
                props.put("mail.smtp.auth", "true");
                session = Session.getInstance(props, new SMTPAuthenticator(smtpUser, password));
            } else {
                session = Session.getInstance(props, null);
            }
            session.setDebug(debug);

            // create a new MimeMessage object (using the Session created above)
            Message mimeMessage = new MimeMessage(session);
            mimeMessage.setFrom(new InternetAddress(from));
            mimeMessage.setRecipients(Message.RecipientType.TO,
                    new InternetAddress[] { new InternetAddress(to) });
            mimeMessage.setSubject(subject);
            mimeMessage.setContent(body.toString(), contentType);
            if (mailHost.trim().equals("")) {
                log.info("No Mail Host.  Would have sent:");
                log.info("From: " + from);
                log.info("To: " + to);
                log.info("Subject: " + subject);
                log.info(mimeMessage.getContent());
            } else {
                Transport.send(mimeMessage);
                sent++;
            }
            message.setSent(new Date());
        } catch (Throwable t) {
            message.failedAttempt();
            if (message.getAttempts() >= maxAttempts) {
                message.setExpires(new Timestamp(System.currentTimeMillis()));
            }
            log.error(t.getMessage(), t);
        }
    }
    return sent;
}

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

/**
 * Retrieve mail for user./*from w w w  .  j a v a2 s.  com*/
 *
 * @param userType = "P" if logged in user is a provider
 *                   "T" if logged in user is a patient
 * @param userId = unique id of logged in user.
 * @param login = email server user name of logged in user.
 * @param pswd  = password of logged in user.
 * @param folderName = 
 * @param displayName = full name
 * @param onlyNew =
 *
 * @return
 * @throws java.lang.Exception
 */
//private  //DBG ONLY - REMOVE COMMENT MARKS
public List<SummaryData> retrieveMail(String userType, String userId, String patientId, String login,
        String pswd, String folderName, String patientName, boolean onlyNew, String mailHost, String mailUrl)
        throws Exception, DatatypeConfigurationException {
    List<SummaryData> dataList = new LinkedList<SummaryData>();
    IMAPSSLStore sslStore = null;
    IMAPFolder currentFolder = null;
    String folderToOpen = folderName;

    System.out.println("===> retrieveMail Incoming params:");
    System.out.println("===>     mailHost=" + mailHost);
    System.out.println("===>      mailUrl=" + mailUrl);
    System.out.println("===>    maillogin=" + login);
    System.out.println("===>   folderName=" + folderName);
    try {
        //Get session
        Session session = Session.getInstance(new Properties());
        URLName urlName = new URLName(mailUrl);
        //Get the sslStore
        sslStore = new IMAPSSLStore(session, urlName);
        sslStore.connect(mailHost, login, pswd);

        folderToOpen = this.mapKmrLocationToImapFolder(folderName, this.host);

        currentFolder = (IMAPFolder) sslStore.getFolder(folderToOpen);
        currentFolder.open(Folder.READ_ONLY);

        Message[] allMessages = currentFolder.getMessages();

        GregorianCalendar cal = new GregorianCalendar();

        System.out.println("====> FILTER PARAMS for Emails:");
        System.out.println("====>     folder = " + folderToOpen);
        System.out.println("====>     User   = " + login);
        //            System.out.println("====>     from   = "+ patientName +"/"+ patientEmail);
        //            System.out.println("====>     ptid   = "+ patientId);
        System.out.println("====> Total Emails found = " + allMessages.length);
        System.out.println();

        // TMN - CHECK SLOW PERFORMANCE ISSUE HERE:

        //Loop through each email and find ONLY the ones required for return.
        for (Message msg : allMessages) {
            if (msg == null) {
                continue;
            }

            // Keep this in case we want to search entire message
            //
            //                OutputStream os = new ByteArrayOutputStream();
            //                msg.writeTo(os);
            //                String msgContent = os.toString();

            SummaryData summaryData = new SummaryData();
            summaryData.setDataSource(DATA_SOURCE);

            String from = "";
            Address[] fromAddr = msg.getFrom();

            if (fromAddr != null && fromAddr.length > 0) {

                String fromFull = fromAddr[0].toString();
                from = getContactIdFromEmail(extractEmailAddressFromSender(fromFull));

                //System.out.println("retrieveMail: FROM=" + fromFull + " ldap.cn=" + from);

            }

            //------------------------------------------------------
            //FILTERING: Check to exclude email if
            //     0) patientId is passed in as a param
            // AND 1) email does NOT contain PATIENTID=<patientId>
            // AND 2) email FROM field <> patientName
            // AND 3) email FROM field <> patientEmail.
            //
            // because must becoming from EMR inbox and looking for emails
            // addressed to userId BUT only ABOUT or FROM patientId.
            //------------------------------------------------------

            summaryData.setFrom(from);
            summaryData.setAuthor(summaryData.getFrom());
            cal.setTime(msg.getReceivedDate());
            summaryData.setDateCreated(DatatypeFactory.newInstance().newXMLGregorianCalendar(cal));

            summaryData.setDescription(msg.getSubject());

            summaryData.setItemId(userType + userId + ITEM_ID_SEPARATER + msg.getFolder().getName()
                    + ITEM_ID_SEPARATER + msg.getHeader("Message-ID")[0]);

            //this.printMsgIdSubject(msg); //DBG printout

            boolean msgRead = msg.isSet(Flags.Flag.SEEN);
            addNameValue(summaryData.getItemValues(), ITEM_READ, String.valueOf(msgRead));

            boolean msgStar = msg.isSet(Flags.Flag.FLAGGED);
            if (msgStar) {
                addNameValue(summaryData.getItemValues(), ITEM_STARRED, "Starred");
            }

            addNameValue(summaryData.getItemValues(), ITEM_REPLIED,
                    String.valueOf(msg.isSet(Flags.Flag.ANSWERED)));
            addNameValue(summaryData.getItemValues(), "MESSAGE_TYPE", msg.getFolder().getName());
            if (onlyNew) {
                if (!msg.isSet(Flags.Flag.SEEN)) {
                    dataList.add(summaryData);
                }
            } else {
                dataList.add(summaryData);
            }
        }

    } catch (MessagingException me) {
        log.error("Error in processing email");
        me.printStackTrace();
    } finally {
        // Close connections

        if (currentFolder != null) {
            try {
                currentFolder.close(false);
            } catch (Exception e) {
            }
        }

        if (sslStore != null) {
            try {
                sslStore.close();
            } catch (Exception e) {
            }
        }
    }

    return dataList;
}

From source file:org.zilverline.core.IMAPCollection.java

/**
 * Index one message./*  ww w.j  ava2 s . c  o  m*/
 */
private void indexMessage(final Document doc, final Message m) throws MessagingException, IOException {
    if (stopRequested) {
        log.info("Indexing stops, due to request");
        return;
    }
    final long uid = ((UIDFolder) m.getFolder()).getUID(m);

    // form a URL that mozilla seems to accept. Couldn't get it to accept
    // what I thought was the standard

    String urlPrefix = "imap://" + user + "@" + host + ":143/fetch%3EUID%3E/";

    final String url = urlPrefix + m.getFolder().getFullName() + "%3E" + uid;
    doc.add(Field.Text("name", url));

    final String subject = m.getSubject();
    final Date recv = m.getReceivedDate();
    final Date sent = m.getSentDate();
    log.info("Folder: " + m.getFolder().getFullName() + ": Message received " + recv + ", subject: " + subject);
    // -------------------------------------------------------
    // data gathered, now add to doc

    if (subject != null) {
        doc.add(Field.Text(F_SUBJECT, m.getSubject()));
        doc.add(Field.Text("title", m.getSubject()));
    }

    if (recv != null) {
        doc.add(Field.Keyword(F_RECEIVED, DateTools.timeToString(recv.getTime(), DateTools.Resolution.SECOND)));
    }

    if (sent != null) {
        doc.add(Field.Keyword(F_SENT, DateTools.timeToString(sent.getTime(), DateTools.Resolution.SECOND)));
        // store date as yyyyMMdd
        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        String dfString = df.format(new Date(sent.getTime()));
        doc.add(Field.Keyword("modified", dfString));
    }

    doc.add(Field.Keyword(F_URL, url));

    Address[] addrs = m.getAllRecipients();
    if (addrs != null) {
        for (int j = 0; j < addrs.length; j++) {
            doc.add(Field.Keyword(F_TO, "" + addrs[j]));
        }
    }

    addrs = m.getFrom();
    if (addrs != null) {
        for (int j = 0; j < addrs.length; j++) {
            doc.add(Field.Keyword(F_FROM, "" + addrs[j]));
            doc.add(Field.Keyword("author", "" + addrs[j]));
        }
    }
    addrs = m.getReplyTo();
    if (addrs != null) {
        for (int j = 0; j < addrs.length; j++) {
            doc.add(Field.Keyword(F_REPLY_TO, "" + addrs[j]));
        }
    }

    doc.add(Field.Keyword(F_UID, "" + uid));

    // could ignore docs that have the deleted flag set
    for (int j = 0; j < FLAGS.length; j++) {
        boolean val = m.isSet(FLAGS[j]);
        doc.add(Field.Keyword(SFLAGS[j], (val ? "true" : "false")));
    }

    // now special case for mime
    if (m instanceof MimeMessage) {
        // mime++;
        MimeMessage mm = (MimeMessage) m;
        log.debug("index, adding MimeMessage " + m.getFileName());
        indexMimeMessage(doc, mm);

    } else {
        // nmime++;

        final DataHandler dh = m.getDataHandler();
        log.debug("index, adding (non-MIME) Content " + m.getFileName());
        doc.add(Field.Text(F_CONTENTS, new InputStreamReader(dh.getInputStream())));
    }
}

From source file:com.jlgranda.fede.ejb.mail.reader.FacturaElectronicaMailReader.java

/**
 * Obtiene una lista de objetos <tt>FacturaReader</tt> desde el mensaje de correo, si existe
 *
 * @param mime4jMessage/*from  w  w  w .  j a  v a2s.c  o  m*/
 * @return lista de instancias instancia <tt>FacturaReader</tt> si existe la factura, null
 * en caso contrario
 */
private List<FacturaReader> handleMessage(org.apache.james.mime4j.dom.Message mime4jMessage)
        throws IOException, Exception {
    List<FacturaReader> result = new ArrayList<>();
    ByteArrayOutputStream os = null;
    String filename = null;
    Factura factura = null;
    EmailHelper emailHelper = new EmailHelper();
    if (mime4jMessage.isMultipart()) {
        org.apache.james.mime4j.dom.Multipart mime4jMultipart = (org.apache.james.mime4j.dom.Multipart) mime4jMessage
                .getBody();
        emailHelper.parseBodyParts(mime4jMultipart);
        //Obtener la factura en los adjuntos
        if (emailHelper.getAttachments().isEmpty()) {
            //If it's single part message, just get text body  
            String text = emailHelper.getHtmlBody().toString();
            emailHelper.getTxtBody().append(text);
            if (mime4jMessage.getSubject().contains("Ghost")) {

                String url = FacturaUtil.extraerURL(emailHelper.getHtmlBody().toString(), "<a href=\"",
                        "\" target=\"_blank\">Descarga formato XML</a>");
                if (url != null) {
                    result.add(FacturaElectronicaURLReader.getFacturaElectronica(url));
                }
            }
        } else {
            for (Entity entity : emailHelper.getAttachments()) {
                filename = EmailHelper.getFilename(entity);

                //if (entity.getBody() instanceof BinaryBody) {
                if (("application/octet-stream".equalsIgnoreCase(entity.getMimeType())
                        || "application/xml".equalsIgnoreCase(entity.getMimeType())
                        || "text/xml".equalsIgnoreCase(entity.getMimeType())
                        || "text/plain".equalsIgnoreCase(entity.getMimeType()))
                        && (filename != null && filename.endsWith(".xml"))) {
                    //attachFiles += part.getFileName() + ", ";
                    os = EmailHelper.writeBody(entity.getBody());
                    factura = FacturaUtil.read(os.toString());
                    if (factura != null) {
                        result.add(new FacturaReader(factura, os.toString(), entity.getFilename(),
                                mime4jMessage.getFrom().get(0).getAddress()));
                    }
                } else if (("application/octet-stream".equalsIgnoreCase(entity.getMimeType())
                        || "aplication/xml".equalsIgnoreCase(entity.getMimeType())
                        || "text/xml".equalsIgnoreCase(entity.getMimeType()))
                        && (filename != null && filename.endsWith(".zip"))) {
                    //http://www.java2s.com/Tutorial/Java/0180__File/UnzipusingtheZipInputStream.htm    
                    os = EmailHelper.writeBody(entity.getBody());
                    ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(os.toByteArray()));
                    try {
                        ZipEntry entry = null;
                        String tmp = null;
                        ByteArrayOutputStream fout = null;
                        while ((entry = zis.getNextEntry()) != null) {
                            if (entry.getName().endsWith(".xml")) {
                                //logger.debug("Unzipping {}", entry.getFilename());
                                fout = new ByteArrayOutputStream();
                                for (int c = zis.read(); c != -1; c = zis.read()) {
                                    fout.write(c);
                                }

                                tmp = new String(fout.toByteArray(), Charset.defaultCharset());

                                factura = FacturaUtil.read(tmp);
                                if (factura != null) {
                                    result.add(new FacturaReader(factura, tmp, entity.getFilename()));
                                }
                                fout.close();
                            }
                            zis.closeEntry();
                        }
                        zis.close();

                    } finally {
                        IOUtils.closeQuietly(os);
                        IOUtils.closeQuietly(zis);
                    }
                } else if ("message/rfc822".equalsIgnoreCase(entity.getMimeType())) {
                    if (entity.getBody() instanceof org.apache.james.mime4j.message.MessageImpl) {
                        result.addAll(
                                handleMessage((org.apache.james.mime4j.message.MessageImpl) entity.getBody()));
                    }
                }
            }
        }
    } else {
        //If it's single part message, just get text body  
        String text = emailHelper.getTxtPart(mime4jMessage);
        emailHelper.getTxtBody().append(text);
        if (mime4jMessage.getSubject().contains("Ghost")) {

            String url = FacturaUtil.extraerURL(emailHelper.getHtmlBody().toString(), "<a href=\"",
                    "\" target=\"_blank\">Descarga formato XML</a>");
            if (url != null) {
                result.add(FacturaElectronicaURLReader.getFacturaElectronica(url));
            }
        }
    }
    return result;
}

From source file:org.nuclos.server.ruleengine.RuleInterface.java

/**
 *
 * @param pop3Host//  w  ww.  j  a  v  a 2  s .  co  m
 * @param pop3Port
 * @param pop3User
 * @param pop3Password
 * @param remove
 * @return
 * @throws NuclosFatalRuleException
 */
public List<NuclosMail> getMails(String pop3Host, String pop3Port, final String pop3User,
        final String pop3Password, boolean remove) throws NuclosFatalRuleException {
    try {
        Properties properties = new Properties();
        properties.setProperty("mail.pop3.host", pop3Host);
        properties.setProperty("mail.pop3.port", pop3Port);
        properties.setProperty("mail.pop3.auth", "true");
        properties.setProperty("mail.pop3.socketFactory.class", "javax.net.DefaultSocketFactory");

        Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(pop3User, pop3Password);
            }
        });

        session.setDebug(true);
        Store store = session.getStore("pop3");
        store.connect();

        Folder folder = store.getFolder("INBOX");
        if (remove) {
            folder.open(Folder.READ_WRITE);
        } else {
            folder.open(Folder.READ_ONLY);
        }

        List<NuclosMail> result = new ArrayList<NuclosMail>();

        Message message[] = folder.getMessages();
        for (int i = 0; i < message.length; i++) {
            Message m = message[i];
            NuclosMail mail = new NuclosMail();
            logger.debug("Received mail: From: " + Arrays.toString(m.getFrom()) + "; To: "
                    + Arrays.toString(m.getAllRecipients()) + "; ContentType: " + m.getContentType()
                    + "; Subject: " + m.getSubject() + "; Sent: " + m.getSentDate());

            Address[] senders = m.getFrom();
            if (senders.length == 1 && senders[0] instanceof InternetAddress) {
                mail.setFrom(((InternetAddress) senders[0]).getAddress());
            } else {
                mail.setFrom(Arrays.toString(m.getFrom()));
            }
            mail.setTo(Arrays.toString(m.getRecipients(RecipientType.TO)));
            mail.setSubject(m.getSubject());

            if (m.isMimeType("text/plain")) {
                mail.setMessage((String) m.getContent());
            } else {
                Multipart mp = (Multipart) m.getContent();
                for (int j = 0; j < mp.getCount(); j++) {
                    Part part = mp.getBodyPart(j);
                    String disposition = part.getDisposition();
                    MimeBodyPart mimePart = (MimeBodyPart) part;
                    logger.debug(
                            "Disposition: " + disposition + "; Part ContentType: " + mimePart.getContentType());

                    if (disposition == null
                            && (mimePart.isMimeType("text/plain") || mimePart.isMimeType("text/html"))) {
                        mail.setMessage((String) mimePart.getDataHandler().getContent());
                    }
                }
                getAttachments(mp, mail);
            }

            result.add(mail);

            if (remove) {
                m.setFlag(Flags.Flag.DELETED, true);
            }
        }

        if (remove) {
            folder.close(true);
        } else {
            folder.close(false);
        }

        store.close();

        return result;
    } catch (Exception e) {
        throw new NuclosFatalRuleException(e);
    }
}

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();//from  ww  w. ja v  a 2 s  . c o  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:org.apache.manifoldcf.crawler.connectors.email.EmailConnector.java

/** Process a set of documents.
* This is the method that should cause each document to be fetched, processed, and the results either added
* to the queue of documents for the current job, and/or entered into the incremental ingestion manager.
* The document specification allows this class to filter what is done based on the job.
* The connector will be connected before this method can be called.
*@param documentIdentifiers is the set of document identifiers to process.
*@param statuses are the currently-stored document versions for each document in the set of document identifiers
* passed in above.// www .j  a v a  2  s  .  com
*@param activities is the interface this method should use to queue up new document references
* and ingest documents.
*@param jobMode is an integer describing how the job is being run, whether continuous or once-only.
*@param usesDefaultAuthority will be true only if the authority in use for these documents is the default one.
*/
@Override
public void processDocuments(String[] documentIdentifiers, IExistingVersions statuses, Specification spec,
        IProcessActivity activities, int jobMode, boolean usesDefaultAuthority)
        throws ManifoldCFException, ServiceInterruption {

    List<String> requiredMetadata = new ArrayList<String>();
    for (int i = 0; i < spec.getChildCount(); i++) {
        SpecificationNode sn = spec.getChild(i);
        if (sn.getType().equals(EmailConfig.NODE_METADATA)) {
            String metadataAttribute = sn.getAttributeValue(EmailConfig.ATTRIBUTE_NAME);
            requiredMetadata.add(metadataAttribute);
        }
    }

    // Keep a cached set of open folders
    Map<String, Folder> openFolders = new HashMap<String, Folder>();
    try {

        for (String documentIdentifier : documentIdentifiers) {
            String versionString = "_" + urlTemplate; // NOT empty; we need to make ManifoldCF understand that this is a document that never will change.

            // Check if we need to index
            if (!activities.checkDocumentNeedsReindexing(documentIdentifier, versionString))
                continue;

            String compositeID = documentIdentifier;
            String version = versionString;
            String folderName = extractFolderNameFromDocumentIdentifier(compositeID);
            String id = extractEmailIDFromDocumentIdentifier(compositeID);

            String errorCode = null;
            String errorDesc = null;
            Long fileLengthLong = null;
            long startTime = System.currentTimeMillis();
            try {
                try {
                    Folder folder = openFolders.get(folderName);
                    if (folder == null) {
                        getSession();
                        OpenFolderThread oft = new OpenFolderThread(session, folderName);
                        oft.start();
                        folder = oft.finishUp();
                        openFolders.put(folderName, folder);
                    }

                    if (Logging.connectors.isDebugEnabled())
                        Logging.connectors.debug("Email: Processing document identifier '" + compositeID + "'");
                    SearchTerm messageIDTerm = new MessageIDTerm(id);

                    getSession();
                    SearchMessagesThread smt = new SearchMessagesThread(session, folder, messageIDTerm);
                    smt.start();
                    Message[] message = smt.finishUp();

                    String msgURL = makeDocumentURI(urlTemplate, folderName, id);

                    Message msg = null;
                    for (Message msg2 : message) {
                        msg = msg2;
                    }
                    if (msg == null) {
                        // email was not found
                        activities.deleteDocument(id);
                        continue;
                    }

                    if (!activities.checkURLIndexable(msgURL)) {
                        errorCode = activities.EXCLUDED_URL;
                        errorDesc = "Excluded because of URL ('" + msgURL + "')";
                        activities.noDocument(id, version);
                        continue;
                    }

                    long fileLength = msg.getSize();
                    if (!activities.checkLengthIndexable(fileLength)) {
                        errorCode = activities.EXCLUDED_LENGTH;
                        errorDesc = "Excluded because of length (" + fileLength + ")";
                        activities.noDocument(id, version);
                        continue;
                    }

                    Date sentDate = msg.getSentDate();
                    if (!activities.checkDateIndexable(sentDate)) {
                        errorCode = activities.EXCLUDED_DATE;
                        errorDesc = "Excluded because of date (" + sentDate + ")";
                        activities.noDocument(id, version);
                        continue;
                    }

                    String mimeType = "text/plain";
                    if (!activities.checkMimeTypeIndexable(mimeType)) {
                        errorCode = activities.EXCLUDED_DATE;
                        errorDesc = "Excluded because of mime type ('" + mimeType + "')";
                        activities.noDocument(id, version);
                        continue;
                    }

                    RepositoryDocument rd = new RepositoryDocument();
                    rd.setFileName(msg.getFileName());
                    rd.setMimeType(mimeType);
                    rd.setCreatedDate(sentDate);
                    rd.setModifiedDate(sentDate);

                    String subject = StringUtils.EMPTY;
                    for (String metadata : requiredMetadata) {
                        if (metadata.toLowerCase().equals(EmailConfig.EMAIL_TO)) {
                            Address[] to = msg.getRecipients(Message.RecipientType.TO);
                            String[] toStr = new String[to.length];
                            int j = 0;
                            for (Address address : to) {
                                toStr[j] = address.toString();
                            }
                            rd.addField(EmailConfig.EMAIL_TO, toStr);
                        } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_FROM)) {
                            Address[] from = msg.getFrom();
                            String[] fromStr = new String[from.length];
                            int j = 0;
                            for (Address address : from) {
                                fromStr[j] = address.toString();
                            }
                            rd.addField(EmailConfig.EMAIL_TO, fromStr);

                        } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_SUBJECT)) {
                            subject = msg.getSubject();
                            rd.addField(EmailConfig.EMAIL_SUBJECT, subject);
                        } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_BODY)) {
                            Multipart mp = (Multipart) msg.getContent();
                            for (int k = 0, n = mp.getCount(); k < n; k++) {
                                Part part = mp.getBodyPart(k);
                                String disposition = part.getDisposition();
                                if ((disposition == null)) {
                                    MimeBodyPart mbp = (MimeBodyPart) part;
                                    if (mbp.isMimeType(EmailConfig.MIMETYPE_TEXT_PLAIN)) {
                                        rd.addField(EmailConfig.EMAIL_BODY, mbp.getContent().toString());
                                    } else if (mbp.isMimeType(EmailConfig.MIMETYPE_HTML)) {
                                        rd.addField(EmailConfig.EMAIL_BODY, mbp.getContent().toString()); //handle html accordingly. Returns content with html tags
                                    }
                                }
                            }
                        } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_DATE)) {
                            rd.addField(EmailConfig.EMAIL_DATE, sentDate.toString());
                        } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_ATTACHMENT_ENCODING)) {
                            Multipart mp = (Multipart) msg.getContent();
                            if (mp != null) {
                                String[] encoding = new String[mp.getCount()];
                                for (int k = 0, n = mp.getCount(); k < n; k++) {
                                    Part part = mp.getBodyPart(k);
                                    String disposition = part.getDisposition();
                                    if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)
                                            || (disposition.equals(Part.INLINE))))) {
                                        encoding[k] = part.getFileName().split("\\?")[1];

                                    }
                                }
                                rd.addField(EmailConfig.ENCODING_FIELD, encoding);
                            }
                        } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_ATTACHMENT_MIMETYPE)) {
                            Multipart mp = (Multipart) msg.getContent();
                            String[] MIMEType = new String[mp.getCount()];
                            for (int k = 0, n = mp.getCount(); k < n; k++) {
                                Part part = mp.getBodyPart(k);
                                String disposition = part.getDisposition();
                                if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)
                                        || (disposition.equals(Part.INLINE))))) {
                                    MIMEType[k] = part.getContentType();

                                }
                            }
                            rd.addField(EmailConfig.MIMETYPE_FIELD, MIMEType);
                        }
                    }

                    InputStream is = msg.getInputStream();
                    try {
                        rd.setBinary(is, fileLength);
                        activities.ingestDocumentWithException(id, version, msgURL, rd);
                        errorCode = "OK";
                        fileLengthLong = new Long(fileLength);
                    } finally {
                        is.close();
                    }
                } catch (InterruptedException e) {
                    throw new ManifoldCFException(e.getMessage(), ManifoldCFException.INTERRUPTED);
                } catch (MessagingException e) {
                    errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT);
                    errorDesc = e.getMessage();
                    handleMessagingException(e, "processing email");
                } catch (IOException e) {
                    errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT);
                    errorDesc = e.getMessage();
                    handleIOException(e, "processing email");
                    throw new ManifoldCFException(e.getMessage(), e);
                }
            } catch (ManifoldCFException e) {
                if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)
                    errorCode = null;
                throw e;
            } finally {
                if (errorCode != null)
                    activities.recordActivity(new Long(startTime), EmailConfig.ACTIVITY_FETCH, fileLengthLong,
                            documentIdentifier, errorCode, errorDesc, null);
            }
        }
    } finally {
        for (Folder f : openFolders.values()) {
            try {
                CloseFolderThread cft = new CloseFolderThread(session, f);
                cft.start();
                cft.finishUp();
            } catch (InterruptedException e) {
                throw new ManifoldCFException(e.getMessage(), ManifoldCFException.INTERRUPTED);
            } catch (MessagingException e) {
                handleMessagingException(e, "closing folders");
            }
        }
    }

}

From source file:com.sonicle.webtop.mail.Service.java

public boolean sendMsg(Identity ident, Message msg) {
    if (ident == null) {
        try {//from   w w w .  j av  a  2s. c  om
            ident = findIdentity((InternetAddress) (msg.getFrom()[0]));
        } catch (Exception exc) {

        }
    }
    String sentfolder = getSentFolder(ident);
    MailAccount account = getAccount(ident);
    try {
        Transport.send(msg);
        saveSent(account, msg, sentfolder);
        return true;

    } catch (Exception ex) {
        Service.logger.error("Exception", ex);
        return false;
    }

}

From source file:com.sonicle.webtop.mail.Service.java

public void processPortletMail(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    ArrayList<JsPreviewMessage> items = new ArrayList<>();

    try {/*from  w ww .  j a  v  a2  s .c o m*/
        MailAccount account = getAccount(request);
        String query = ServletUtils.getStringParameter(request, "query", null);
        int visibleRows = 0;
        int maxVisibleRows = 20;

        if (query == null) {
            String folderId = account.getInboxFolderFullName();
            FolderCache fc = account.getFolderCache(folderId);
            Message msgs[] = fc.getMessages(FolderCache.SORT_BY_DATE, false, true, -1, true, false, null,
                    false);
            if (msgs != null)
                fc.fetch(msgs, getMessageFetchProfile(), 0, 50);
            else
                msgs = new Message[0];

            for (Message msg : msgs) {
                SonicleIMAPMessage simsg = (SonicleIMAPMessage) msg;

                InternetAddress iafrom = null;
                Address vfrom[] = msg.getFrom();
                if (vfrom != null && vfrom.length > 0) {
                    Address afrom = vfrom[0];
                    if (afrom instanceof InternetAddress) {
                        iafrom = (InternetAddress) afrom;
                    }
                }

                Address[] rcpts = msg.getRecipients(Message.RecipientType.TO);
                ArrayList<InternetAddress> tos = new ArrayList<>();
                if (rcpts != null)
                    for (Address ato : rcpts) {
                        if (ato instanceof InternetAddress) {
                            InternetAddress iato = (InternetAddress) ato;
                            tos.add(iato);
                        }
                    }

                String msgtext = "";
                if (visibleRows < maxVisibleRows) {
                    msgtext = MailUtils.peekText(simsg);
                    if (msgtext == null)
                        msgtext = "";
                    else {
                        msgtext = msgtext.trim();
                        if (msgtext.length() > 100)
                            msgtext = msgtext.substring(0, 100);
                    }
                    ++visibleRows;
                }

                String from = iafrom != null
                        ? (iafrom.getPersonal() != null ? iafrom.getPersonal() : iafrom.getAddress())
                        : "";
                String to = "";
                if (tos.size() > 0) {
                    boolean first = true;
                    for (InternetAddress iato : tos) {
                        if (!first)
                            to += "; ";
                        to += (iato.getPersonal() != null ? iato.getPersonal() : iato.getAddress());
                        first = false;
                    }
                }

                JsPreviewMessage jsmsg = new JsPreviewMessage(simsg.getUID(), folderId,
                        getInternationalFolderName(account.getFolderCache(folderId)), simsg.getSubject(), from,
                        to, msg.getReceivedDate(), msgtext);
                items.add(jsmsg);
            }
        } else {
        }

        new JsonResult(items).printTo(out);

    } catch (Exception ex) {
        logger.error("Error in PortletMail", ex);
        new JsonResult(false, "Error").printTo(out);
    }
}