Example usage for javax.mail Message setFlag

List of usage examples for javax.mail Message setFlag

Introduction

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

Prototype

public void setFlag(Flags.Flag flag, boolean set) throws MessagingException 

Source Link

Document

Set the specified flag on this message to the specified value.

Usage

From source file:com.email.ReceiveEmail.java

/**
 * This account fetches emails from a specified account and marks the emails
 * as seen, only touches the email account does not delete or move any
 * information.// w w  w . ja v a  2  s . c o  m
 *
 * @param account SystemEmailModel
 */
public static void fetchEmail(SystemEmailModel account) {
    Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account);
    Properties properties = EmailProperties.setEmailInProperties(account);

    try {
        Session session = Session.getInstance(properties, auth);
        Store store = session.getStore();
        store.connect(account.getIncomingURL(), account.getIncomingPort(), account.getUsername(),
                account.getPassword());
        Folder fetchFolder = store.getFolder(account.getIncomingFolder());
        if (account.getIncomingFolder().trim().equals("")) {
            fetchFolder = store.getFolder("INBOX");
        }

        if (fetchFolder.exists()) {
            fetchFolder.open(Folder.READ_WRITE);
            Message[] msgs = fetchFolder.getMessages();

            // USE THIS FOR UNSEEN MAIL TO SEEN MAIL
            //Flags seen = new Flags(Flags.Flag.SEEN);
            //FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
            //Message[] msgs = fetchFolder.search(unseenFlagTerm);
            //fetchFolder.setFlags(msgs, seen, true);
            if (msgs.length > 0) {
                List<String> messageList = new ArrayList<>();

                for (Message msg : msgs) {
                    boolean notDuplicate = true;
                    String headerText = Arrays.toString(msg.getHeader("Message-ID"));

                    for (String header : messageList) {
                        if (header.equals(headerText)) {
                            notDuplicate = false;
                            break;
                        }
                    }

                    if (notDuplicate) {
                        //Add to header to stop duplicates
                        messageList.add(headerText);
                        attachmentCount = 1;
                        attachmentList = new ArrayList<>();

                        //Setup Email For dbo.Email
                        EmailMessageModel eml = new EmailMessageModel();
                        String emailTime = String.valueOf(new Date().getTime());
                        eml.setSection(account.getSection());
                        eml = saveEnvelope(msg, msg, eml);
                        eml.setId(EMail.InsertEmail(eml));

                        //After Email has been inserted Gather Attachments
                        saveAttachments(msg, msg, eml);

                        //Create Email Body
                        eml = EmailBodyToPDF.createEmailBodyIn(eml, emailTime, attachmentList);

                        //Insert Email Body As Attachment (so it shows up in attachment table during Docketing)
                        EmailAttachment.insertEmailAttachment(eml.getId(), eml.getEmailBodyFileName());

                        //Flag email As ready to file so it is available in the docket tab of SERB3.0
                        eml.setReadyToFile(1);
                        EMail.setEmailReadyToFile(eml);
                    }

                    if (deleteEmailEnabled) {
                        //  Will Delete message from server
                        //  Un Comment line below to run
                        msg.setFlag(Flags.Flag.DELETED, true);
                    }
                }
            }
            fetchFolder.close(true);
            store.close();
        }
    } catch (MessagingException ex) {
        if (ex != null) {
            System.out.println("Unable to connect to email Server for: " + account.getEmailAddress()
                    + "\nPlease ensure you are connected to the network and" + " try again.");
        }
        ExceptionHandler.Handle(ex);
    }
}

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

public void storeContents(long folderId, long[] remoteMessageIds) throws IOException, PortalException {

    Folder jxFolder = null;//from   w  w w. j  av  a  2  s  .co m

    try {
        jxFolder = openFolder(folderId);

        Message[] jxMessages = getMessagesByUID(jxFolder, remoteMessageIds);

        FetchProfile fetchProfile = new FetchProfile();

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

        jxFolder.fetch(jxMessages, fetchProfile);

        for (Message jxMessage : jxMessages) {
            String flags = getFlags(jxMessage);

            long remoteMessageId = getUID(jxFolder, jxMessage);

            com.liferay.mail.model.Message message = MessageLocalServiceUtil.getMessage(folderId,
                    remoteMessageId);

            StringBundler bodyPlain = new StringBundler();
            StringBundler bodyHtml = new StringBundler();
            List<MailFile> mailFiles = new ArrayList<>();

            getParts(_user.getUserId(), bodyPlain, bodyHtml, StringPool.BLANK, jxMessage, mailFiles);

            if (bodyHtml.length() == 0) {
                if (bodyPlain.length() == 0) {
                    bodyHtml.append("&nbsp;");
                } else {
                    bodyHtml = bodyPlain;
                }
            }

            if (flags.indexOf(MailConstants.FLAG_SEEN) == -1) {
                jxMessage.setFlag(Flags.Flag.SEEN, false);
            }

            AttachmentLocalServiceUtil.deleteAttachments(message.getCompanyId(), message.getMessageId());

            for (MailFile mailFile : mailFiles) {
                AttachmentLocalServiceUtil.addAttachment(_user.getUserId(), message.getMessageId(),
                        mailFile.getContentPath(), mailFile.getFileName(), mailFile.getSize(),
                        mailFile.getFile());
            }

            MessageLocalServiceUtil.updateContent(message.getMessageId(), bodyHtml.toString(), flags);
        }
    } catch (MessagingException me) {
        throw new MailException(me);
    } finally {
        closeFolder(jxFolder, false);
    }
}

From source file:org.apache.nifi.processors.email.ConsumeEWS.java

/**
 * Disposes the message by converting it to a {@link FlowFile} transferring
 * it to the REL_SUCCESS relationship./* ww w . j  a  v  a  2  s .  c om*/
 */
private void transfer(Message emailMessage, ProcessContext context, ProcessSession processSession) {
    long start = System.nanoTime();
    FlowFile flowFile = processSession.create();

    flowFile = processSession.append(flowFile, new OutputStreamCallback() {
        @Override
        public void process(final OutputStream out) throws IOException {
            try {
                emailMessage.writeTo(out);
            } catch (MessagingException e) {
                throw new IOException(e);
            }
        }
    });

    long executionDuration = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);

    String fromAddressesString = "";
    try {
        Address[] fromAddresses = emailMessage.getFrom();
        if (fromAddresses != null) {
            fromAddressesString = Arrays.asList(fromAddresses).toString();
        }
    } catch (MessagingException e) {
        this.logger.warn("Faild to retrieve 'From' attribute from Message.");
    }

    processSession.getProvenanceReporter().receive(flowFile, this.displayUrl,
            "Received message from " + fromAddressesString, executionDuration);
    this.getLogger().info("Successfully received {} from {} in {} millis",
            new Object[] { flowFile, fromAddressesString, executionDuration });
    processSession.transfer(flowFile, REL_SUCCESS);

    try {
        emailMessage.setFlag(Flags.Flag.DELETED, this.shouldSetDeleteFlag);
    } catch (MessagingException e) {
        this.logger.warn("Failed to set DELETE Flag on the message, data duplication may occur.");
    }
}

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

public void generateMailNotification(String mailStoreProtocol, String mailStoreHost, String mailStoreUserName,
        String mailStorePassword, String notificationType, String fromFilter, String subjectFilter)
        throws Exception {
    Session session = getMailStoreSession(mailStoreProtocol, mailStoreHost, mailStoreUserName,
            mailStorePassword);//from w  ww  .  j a  v a  2 s.co  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_WRITE);

        // check if fromFilter is specified
        List<String> fromFilterList = null;

        if (StringUtils.isNotBlank(fromFilter)) {
            String[] fromFilterArray = StringUtils.split(fromFilter, "|");
            fromFilterList = Arrays.asList(fromFilterArray);
        }

        // check if subjectFilter is specified
        List<String> subjectFilterList = null;
        if (StringUtils.isNotBlank(subjectFilter)) {
            String[] subjectFilterArray = StringUtils.split(subjectFilter, "|");
            subjectFilterList = Arrays.asList(subjectFilterArray);
        }
        Map<String, Object> context = new HashMap<String, Object>();
        // 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 address = fromAddress[0].toString();
            String from = extractFromAddress(address);
            if (StringUtils.isBlank(from)) {
                logger.warn("From Address is not proper " + from);
                return;
            }
            boolean isValidFrom = isValidMatch(fromFilterList, from);

            // filter based on fromFilter specified
            if (null == fromFilterList || isValidFrom) {
                String subject = msg.getSubject();

                boolean isValidSubject = isValidMatch(subjectFilterList, subject);
                if (null == subjectFilterList || isValidSubject) {
                    String toList = parseAddresses(msg.getRecipients(RecipientType.TO));
                    String ccList = parseAddresses(msg.getRecipients(RecipientType.CC));
                    String sentDate = msg.getSentDate().toString();

                    String messageContent = "";
                    try {
                        Object content = msg.getContent();
                        if (content != null) {
                            messageContent = content.toString();
                        }
                    } catch (Exception ex) {
                        messageContent = "[Error downloading content]";
                        ex.printStackTrace();
                    }
                    context.put("from", from);
                    context.put("to", toList);
                    context.put("cc", ccList);
                    context.put("subject", subject);
                    context.put("messagebody", messageContent);
                    context.put("sentdate", sentDate);

                    notificationController.createNotification(notificationType, context);
                    msg.setFlag(Flag.DELETED, true);
                } else {
                    logger.warn("subjectFilter doesn't match");
                }
            } else {
                logger.warn("this email originated from " + address
                        + " , which does not match fromAddress specified in the rule, it should be "
                        + fromFilter.toString());
            }
        }
        // disconnect and delete messages marked as DELETED
        folderInbox.close(true);
        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:com.funambol.email.items.manager.ImapEntityManager.java

/**
 *
 *
 * @param FID folder id String//from ww w.j  a  v a  2s.c  o m
 * @param LUID  String
 * @param emailToAdd  Email
 * @param filter EmailFilter
 * @param funSignature  String
 * @param from  String
 * @param firstname  String
 * @param lastname  String
 * @param username  String
 * @param source_uri  String
 * @param principalId long
 * @return Email
 * @throws EntityException
 */
public Email addEmail(String FID, String LUID, Email emailToAdd, Map serverItems, EmailFilter filter,
        String funSignature, String from, String firstname, String lastname, String username, String source_uri,
        long principalId) throws EntityException, SendingException, RefusedItemException {

    IMAPFolder f = null;
    String fullpath = null;

    // the emailItem could be null
    // i.e. the client send only the read property
    FlagProperties fp = Utility.getFlags(emailToAdd);

    if (emailToAdd != null && emailToAdd.getEmailItem() != null
            && Def.ENCODE_QUOTED_PRINTABLE.equals(emailToAdd.getEmailItem().getEncoding())) {
        try {
            emailToAdd.getEmailItem().setPropertyValue(
                    Utility.decode(emailToAdd.getEmailItem().getStringRFC2822(), Def.ENCODE_QUOTED_PRINTABLE));
            emailToAdd.getEmailItem().setEncoding(null);
        } catch (MessagingException e) {
            throw new EntityException(e);
        }
    }

    try {

        if (FID.equalsIgnoreCase(Def.FOLDER_OUTBOX_ID)) {

            // OUTBOX - sending procedure (email with id starts with "O")

            FID = Def.FOLDER_SENT_ID;

            // convert Email into Message (javaMail)
            Message msg = createMessage(this.imsw.getSession(), emailToAdd, FID, false, fp);

            // save message-ID
            String messageID = Utility.getHeaderMessageID(msg);

            // send message
            Message newMsg = null;
            try {
                newMsg = sendEmail(msg, this.imsw.getSession(), funSignature, from, firstname, lastname);
            } catch (SendingException se) {
                throw new SendingException(se);
            }

            if (newMsg != null) {
                if (messageID != null) {
                    newMsg.setHeader(Def.HEADER_MESSAGE_ID, messageID);
                }
                newMsg.setFlag(Flags.Flag.SEEN, true);
            } else {
                if (messageID != null) {
                    msg.setHeader(Def.HEADER_MESSAGE_ID, messageID);
                }
            }

            if (Def.SERVER_TYPE_AOL.equals(this.serverType) || Def.SERVER_TYPE_GMAIL.equals(this.serverType)) {

                //
                // The email is stored in the SENT folder by the AOL server
                // and Gmail imap.
                //

                // don't save the email in the sent folder
                emailToAdd.setParentId(new Property(Def.FOLDER_OUTBOX_ID));

                String GUID = Utility.createIMAPGUID(Def.FOLDER_OUTBOX_ID, String.valueOf(LUID),
                        String.valueOf(0));
                emailToAdd.setUID(new Property(GUID));

                // if the item is not saved in the sent folder the system
                // doesn't add it into the servetItems list

                return emailToAdd;

            } else {

                // the SENT folder could be disable
                // if it's enabled the system adds the item in the sent
                // folder of the Mail Server

                // get Sent folder name
                fullpath = this.ied.getFullPathFromFID(FID, source_uri, principalId, username);
                if (fullpath == null) {
                    emailToAdd.setParentId(new Property(Def.FOLDER_OUTBOX_ID));
                    String GUID = Utility.createIMAPGUID(Def.FOLDER_OUTBOX_ID, String.valueOf(LUID),
                            String.valueOf(0));
                    emailToAdd.setUID(new Property(GUID));
                    return emailToAdd;
                }

                // open Sent Folder on mail server
                f = (IMAPFolder) this.imsw.getMailDefaultFolder().getFolder(fullpath);

                if (!f.exists()) {
                    emailToAdd.setParentId(new Property(Def.FOLDER_OUTBOX_ID));
                    String GUID = Utility.createIMAPGUID(Def.FOLDER_OUTBOX_ID, String.valueOf(LUID),
                            String.valueOf(0));
                    emailToAdd.setUID(new Property(GUID));
                    return emailToAdd;
                }

                timeStart = System.currentTimeMillis();

                f.open(Folder.READ_WRITE);

                long uid = -1;
                if (this.serverType.equals(Def.SERVER_TYPE_COURIER)) {
                    if (newMsg != null) {
                        uid = this.ied.addEmailByNextUID(f, newMsg);
                    } else {
                        uid = this.ied.addEmailByNextUID(f, msg);
                    }
                } else {
                    if (newMsg != null) {
                        uid = this.ied.addEmailByListener(f, newMsg);
                    } else {
                        uid = this.ied.addEmailByListener(f, msg);
                    }
                }

                emailToAdd.setParentId(new Property(Def.FOLDER_OUTBOX_ID));

                long uidv = f.getUIDValidity();

                String GUID = Utility.createIMAPGUID(Def.FOLDER_OUTBOX_ID, String.valueOf(uid),
                        String.valueOf(uidv));

                emailToAdd.setUID(new Property(GUID));

                // create the object to add in db and in serverItems
                SyncItemInfo sii = createInfo(GUID, msg, null, Def.PROTOCOL_IMAP);

                // add email to the servetItems list
                this.ied.addItemInServerItems(sii, serverItems);

                return emailToAdd;
            }

        } else {

            /**
             * this procedure should be tested with client that syncs
             * items into the the folders: INBOX - SENT - DRAFT - TRASH
             * At the moment the Funambol client doesn't sync the
             * previous folders.
             */

            // INBOX - SENT - DRAFT - TRASH

            if (this.isFolderActive(FID, filter)) {

                fullpath = this.ied.getFullPathFromFID(FID, source_uri, principalId, username);

                if (fullpath == null) {
                    return emailToAdd;
                }

                f = (IMAPFolder) this.imsw.getMailDefaultFolder().getFolder(fullpath);

                if (!f.exists()) {
                    //emailToAdd.setUID(new Property(LUID));
                    return emailToAdd;
                }

                // convert Email into Message (javaMail)
                Message msg = createMessage(this.imsw.getSession(), emailToAdd, FID, false, fp);

                checkIfItHasToBeRefused(msg);

                // add in the folder of the Mail Server
                timeStart = System.currentTimeMillis();

                f.open(Folder.READ_WRITE);

                long uid = -1;
                if (this.serverType.equals(Def.SERVER_TYPE_COURIER)) {
                    uid = this.ied.addEmailByNextUID(f, msg);
                } else {
                    uid = this.ied.addEmailByListener(f, msg);
                }

                long uidv = f.getUIDValidity();

                String GUID = Utility.createIMAPGUID(FID, String.valueOf(uid), String.valueOf(uidv));

                emailToAdd.setUID(new Property(GUID));

                // create the object to add in db and in serverItems
                SyncItemInfo sii = createInfo(GUID, msg, null, Def.PROTOCOL_IMAP);

                if (FID.equalsIgnoreCase(Def.FOLDER_INBOX_ID)) {
                    // add email into the inbox table
                    this.ied.addEmailInDB(sii, username, Def.PROTOCOL_IMAP);
                }

                // add email to the servetItems list
                this.ied.addItemInServerItems(sii, serverItems);

                return emailToAdd;

            } else {

                return emailToAdd;

            }

        }

    } catch (MessagingException me) {
        throw new EntityException(me);
    } catch (SendingException e) {
        throw new SendingException(e);
    } finally {
        if (f != null) {
            try {
                if (f.isOpen()) {
                    f.close(true);
                    timeStop = System.currentTimeMillis();
                    if (log.isTraceEnabled()) {
                        log.trace("insertItem Execution Time: " + (timeStop - timeStart) + " ms");
                    }
                }
            } catch (MessagingException me) {
                throw new EntityException(me);
            }
        }
    }
}

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

public SetMessageResponseType deleteMessage(SetMessageRequestType request) {
    SetMessageResponseType response = new SetMessageResponseType();
    IMAPSSLStore sslStore = null;/*  w  w  w  . j  a  v  a2  s  . c o  m*/
    Folder sourceFolder = null;
    Folder targetFolder = null;
    Properties prop = initializeMailProperties();
    Session session = Session.getDefaultInstance(prop);

    //Get email address and password from LDAP
    String userId = request.getUserId();
    ContactDAO contactDAO = LdapService.getContactDAO();
    ContactDTO foundContact = new ContactDTO();
    List<ContactDTO> contacts = contactDAO.findAllContacts();
    for (ContactDTO contact : contacts) {
        if (contact.getUid() != null && contact.getUid().equals(request.getUserId())) {
            foundContact = contact;
            break;
        }
    }

    String userType = "";
    String[] access = new String[2];
    String userCName = foundContact.getCommonName();
    if (contacts.isEmpty()) {
        log.error("Contact record not found for user: " + userCName);
        response.setMessage("Contact record not found for user: " + userCName);
        response.setSuccessStatus(false);
        return response;
    }

    access = retrieveMailAccess(userCName, foundContact.getUid()); //TMN
    //        if (foundContact.getEmployeeNumber() != null) {
    //            userType = ITEM_ID_PROVIDER;
    //            access = retrieveMailAccess(userType, foundContact.getEmployeeNumber());
    //        }
    //        else {
    //            userType = ITEM_ID_PATIENT;
    //            access = retrieveMailAccess(userType, foundContact.getUid());
    //        }

    if ((access[0] == null) || access[0].isEmpty()) {
        log.error("Contact record not found for user: " + userId);
        response.setMessage("Contact record not found for user: " + userId);
        response.setSuccessStatus(false);
        return response;
    }

    try {

        //--------------------------
        // Set originating folder
        //--------------------------
        sourceFolder = getImapFolder(session, sslStore, access,
                this.mapKmrLocationToImapFolder(request.getLocation(), this.host));

        // Is this really needed if request comes in with location=UserTrash already?
        if (request.getAction().equals("Undelete")) {
            sourceFolder = getImapFolder(session, sslStore, access, "UserTrash");
        }
        sourceFolder.open(Folder.READ_WRITE);

        //--------------------------
        // Set destination folder
        //--------------------------
        if (request.getAction().equals("Delete")) {
            targetFolder = getImapFolder(session, sslStore, access, "UserTrash");
        }
        if (request.getAction().equals("DeleteForever")) {
            targetFolder = getImapFolder(session, sslStore, access, "AdminTrash");
        } else if (request.getAction().equals("Undelete")) {
            targetFolder = getImapFolder(session, sslStore, access, "INBOX");
        }
        targetFolder.open(Folder.READ_WRITE);

        //--------------------------------------------
        // Find the message by the given Message-ID
        //-------------------------------------------
        Message msg = this.findMsgByMessageId(sourceFolder, request.getMessageId());

        if (msg == null) {
            String errmsg = "Msg NOT found for Message-ID=" + request.getMessageId();
            System.out.println("===> deleteMessage: " + errmsg);

            response.setSuccessStatus(false);
            response.setMessage(errmsg);

        } else {

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

            //----------------------
            //copy to new folder
            //----------------------
            Message[] messages = new Message[] { msg };
            sourceFolder.copyMessages(messages, targetFolder);

            //----------------------
            //remove from old folder
            //----------------------
            msg.setFlag(Flags.Flag.DELETED, true);
            sourceFolder.expunge();

            response.setSuccessStatus(true);
        }

    } catch (Exception e) {
        log.error(e.getMessage());
        response.setMessage("Error archiving mail with Zimbra mail server: " + e.getMessage());
        response.setSuccessStatus(false);
        e.printStackTrace();
        return response;
    } finally {
        try {
            sourceFolder.close(false);
            targetFolder.close(false);
        } catch (MessagingException me) {
            me.printStackTrace();
        }
    }

    return response;
}

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

/**
 * {@inheritDoc}//  w  w w .  j a v  a  2s.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:org.accesointeligente.server.robots.ResponseChecker.java

public void connectAndCheck() {
    if (ApplicationProperties.getProperty("email.server") == null
            || ApplicationProperties.getProperty("email.user") == null
            || ApplicationProperties.getProperty("email.password") == null
            || ApplicationProperties.getProperty("email.folder") == null
            || ApplicationProperties.getProperty("email.failfolder") == null
            || ApplicationProperties.getProperty("attachment.directory") == null
            || ApplicationProperties.getProperty("attachment.baseurl") == null) {
        logger.error("Properties are not defined!");
        return;/*from w  w w  .  j a va 2  s.c  om*/
    }

    org.hibernate.Session hibernate = null;

    try {
        session = Session.getInstance(props, null);
        store = session.getStore("imaps");
        store.connect(ApplicationProperties.getProperty("email.server"),
                ApplicationProperties.getProperty("email.user"),
                ApplicationProperties.getProperty("email.password"));

        Folder failbox = store.getFolder(ApplicationProperties.getProperty("email.failfolder"));
        Folder inbox = store.getFolder(ApplicationProperties.getProperty("email.folder"));
        inbox.open(Folder.READ_WRITE);

        for (Message message : inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false))) {
            try {
                logger.info("Sender: " + message.getFrom()[0] + "\tSubject: " + message.getSubject());
                remoteIdentifiers = null;
                messageBody = null;
                remoteIdentifiers = new HashSet<String>();

                if (message.getSubject() != null) {
                    Matcher matcher = pattern.matcher(message.getSubject());

                    if (matcher.matches()) {
                        remoteIdentifiers.add(formatIdentifier(matcher.group(1), matcher.group(2),
                                Integer.parseInt(matcher.group(3))));
                        logger.info("remote identifier: " + formatIdentifier(matcher.group(1), matcher.group(2),
                                Integer.parseInt(matcher.group(3))));
                    }
                }

                Object content = message.getContent();

                if (content instanceof Multipart) {
                    Multipart mp = (Multipart) message.getContent();
                    logger.info("Email content type is Multipart, each part of " + mp.getCount()
                            + " will be processed");

                    for (int i = 0, n = mp.getCount(); i < n; i++) {
                        Part part = mp.getBodyPart(i);
                        logger.info("Part: " + (i + 1) + " of " + mp.getCount());
                        processPart(part);
                    }
                } else if (content instanceof String) {
                    logger.info("Email content type is String");
                    messageBody = (String) content;
                    Matcher matcher;
                    StringTokenizer tokenizer = new StringTokenizer(messageBody);

                    while (tokenizer.hasMoreTokens()) {
                        String token = tokenizer.nextToken();
                        matcher = pattern.matcher(token);

                        if (matcher.matches()) {
                            remoteIdentifiers.add(formatIdentifier(matcher.group(1), matcher.group(2),
                                    Integer.parseInt(matcher.group(3))));
                            logger.info("remote identifier: " + formatIdentifier(matcher.group(1),
                                    matcher.group(2), Integer.parseInt(matcher.group(3))));
                        }
                    }
                } else {
                    logger.info("Email content type isn't String or Multipart");
                    message.setFlag(Flag.SEEN, false);
                    inbox.copyMessages(new Message[] { message }, failbox);
                    message.setFlag(Flag.DELETED, true);
                    inbox.expunge();
                    continue;
                }

                Boolean requestFound = false;
                Matcher matcher = htmlPattern.matcher(messageBody);

                if (matcher.find()) {
                    messageBody = htmlToString(messageBody);
                }

                logger.info("Searching for Request Remote Identifier");
                for (String remoteIdentifier : remoteIdentifiers) {
                    hibernate = HibernateUtil.getSession();
                    hibernate.beginTransaction();

                    Criteria criteria = hibernate.createCriteria(Request.class);
                    criteria.add(Restrictions.eq("remoteIdentifier", remoteIdentifier));
                    Request request = (Request) criteria.uniqueResult();
                    hibernate.getTransaction().commit();

                    if (request != null) {
                        logger.info("Request found for Remote Identifier: " + remoteIdentifier);
                        Response response;

                        // If the attachments haven't been used, use them. Otherwise, copy them.
                        if (!requestFound) {
                            response = createResponse(message.getFrom()[0].toString(), message.getSentDate(),
                                    message.getSubject(), messageBody);
                        } else {
                            response = createResponse(message.getFrom()[0].toString(), message.getSentDate(),
                                    message.getSubject(), messageBody);
                        }

                        hibernate = HibernateUtil.getSession();
                        hibernate.beginTransaction();

                        response.setRequest(request);
                        request.setStatus(RequestStatus.RESPONDED);
                        request.setExpired(RequestExpireType.WITHRESPONSE);
                        request.setResponseDate(new Date());
                        hibernate.update(request);
                        hibernate.update(response);
                        hibernate.getTransaction().commit();
                        requestFound = true;
                    }
                }

                if (!requestFound) {
                    logger.info("Request not found");
                    createResponse(message.getFrom()[0].toString(), message.getSentDate(), message.getSubject(),
                            messageBody);
                    message.setFlag(Flag.SEEN, false);
                    inbox.copyMessages(new Message[] { message }, failbox);
                    message.setFlag(Flag.DELETED, true);
                    inbox.expunge();
                }
            } catch (Exception e) {
                if (hibernate != null && hibernate.isOpen() && hibernate.getTransaction().isActive()) {
                    hibernate.getTransaction().rollback();
                }

                logger.error(e.getMessage(), e);
            }
        }
    } catch (Exception e) {
        if (hibernate != null && hibernate.isOpen() && hibernate.getTransaction().isActive()) {
            hibernate.getTransaction().rollback();
        }

        logger.error(e.getMessage(), e);
    }
}

From source file:be.ibridge.kettle.job.entry.getpop.JobEntryGetPOP.java

public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = new Result(nr);
    result.setResult(false);/*from   w  w  w . j a v a 2s.  c om*/
    result.setNrErrors(1);

    FileObject fileObject = null;

    //Get system properties

    //Properties prop = System.getProperties();
    Properties prop = new Properties();

    //Create session object
    //Session sess = Session.getDefaultInstance(prop,null);
    Session sess = Session.getInstance(prop, null);
    sess.setDebug(true);

    try {

        int nbrmailtoretrieve = Const.toInt(firstmails, 0);
        fileObject = KettleVFS.getFileObject(getRealOutputDirectory());

        // Check if output folder exists
        if (!fileObject.exists()) {
            log.logError(toString(),
                    Messages.getString("JobGetMailsFromPOP.FolderNotExists1.Label") + getRealOutputDirectory()
                            + Messages.getString("JobGetMailsFromPOP.FolderNotExists2.Label"));
        } else {

            String host = getRealServername();
            String user = getRealUsername();
            String pwd = getRealPassword();

            Store st = null;

            if (!getUseSSL()) {

                //Create POP3 object               
                st = sess.getStore("pop3");

                // Try to connect to the server
                st.connect(host, user, pwd);
            } else {
                // Ssupports POP3 connection with SSL, the connection is established via SSL.

                String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

                //Properties pop3Props = new Properties();

                prop.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
                prop.setProperty("mail.pop3.socketFactory.fallback", "false");
                prop.setProperty("mail.pop3.port", getRealSSLPort());
                prop.setProperty("mail.pop3.socketFactory.port", getRealSSLPort());

                URLName url = new URLName("pop3", host, Const.toInt(getRealSSLPort(), 995), "", user, pwd);

                st = new POP3SSLStore(sess, url);

                st.connect();

            }

            log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.LoggedWithUser.Label") + user);

            //Open default folder   INBOX 
            Folder f = st.getFolder("INBOX");
            f.open(Folder.READ_ONLY);

            if (f == null) {
                log.logError(toString(), Messages.getString("JobGetMailsFromPOP.InvalidFolder.Label"));

            } else {

                log.logDetailed(toString(),
                        Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder1.Label") + f.getName()
                                + Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder2.Label")
                                + f.getMessageCount());
                log.logDetailed(toString(),
                        Messages.getString("JobGetMailsFromPOP.TotalNewMessagesFolder1.Label") + f.getName()
                                + Messages.getString("JobGetMailsFromPOP.TotalNewMessagesFolder2.Label")
                                + f.getNewMessageCount());

                // Get emails 
                Message msg_list[] = getPOPMessages(f, retrievemails);

                if (msg_list.length > 0) {
                    List current_file_POP = new ArrayList();
                    List current_filepath_POP = new ArrayList();
                    int nb_email_POP = 1;
                    DateFormat dateFormat = new SimpleDateFormat("hhmmss_mmddyyyy");

                    String startpattern = "name";
                    if (!Const.isEmpty(getRealFilenamePattern())) {
                        startpattern = getRealFilenamePattern();
                    }

                    for (int i = 0; i < msg_list.length; i++)

                    {

                        /*if(msg[i].isMimeType("text/plain"))
                         {
                         log.logDetailed(toString(), "Expediteur: "+msg[i].getFrom()[0]);
                         log.logDetailed(toString(), "Sujet: "+msg[i].getSubject());
                         log.logDetailed(toString(), "Texte: "+(String)msg[i].getContent());
                                
                         }*/

                        if ((nb_email_POP <= nbrmailtoretrieve && retrievemails == 2) || (retrievemails != 2)) {

                            Message msg_POP = msg_list[i];
                            log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.EmailFrom.Label")
                                    + msg_list[i].getFrom()[0]);
                            log.logDetailed(toString(),
                                    Messages.getString("JobGetMailsFromPOP.EmailSubject.Label")
                                            + msg_list[i].getSubject());

                            String localfilename_message = startpattern + "_" + dateFormat.format(new Date())
                                    + "_" + (i + 1) + ".mail";

                            log.logDetailed(toString(),
                                    Messages.getString("JobGetMailsFromPOP.LocalFilename1.Label")
                                            + localfilename_message
                                            + Messages.getString("JobGetMailsFromPOP.LocalFilename2.Label"));

                            File filename_message = new File(getRealOutputDirectory(), localfilename_message);
                            OutputStream os_filename = new FileOutputStream(filename_message);
                            Enumeration enums_POP = msg_POP.getAllHeaders();
                            while (enums_POP.hasMoreElements())

                            {
                                Header header_POP = (Header) enums_POP.nextElement();
                                os_filename.write(new StringBuffer(header_POP.getName()).append(": ")
                                        .append(header_POP.getValue()).append("\r\n").toString().getBytes());
                            }
                            os_filename.write("\r\n".getBytes());
                            InputStream in_POP = msg_POP.getInputStream();
                            byte[] buffer_POP = new byte[1024];
                            int length_POP = 0;
                            while ((length_POP = in_POP.read(buffer_POP, 0, 1024)) != -1) {
                                os_filename.write(buffer_POP, 0, length_POP);
                            }
                            os_filename.close();
                            nb_email_POP++;
                            current_file_POP.add(filename_message);
                            current_filepath_POP.add(filename_message.getPath());

                            if (delete) {
                                log.logDetailed(toString(),
                                        Messages.getString("JobGetMailsFromPOP.DeleteEmail.Label"));
                                msg_POP.setFlag(javax.mail.Flags.Flag.DELETED, true);
                            }
                        }

                    }
                }
                // Close and exit 
                if (f != null)
                    f.close(false);
                if (st != null)
                    st.close();

                f = null;
                st = null;
                sess = null;

                result.setNrErrors(0);
                result.setResult(true);

            }
        }

    }

    catch (NoSuchProviderException e) {
        log.logError(toString(), "provider error: " + e.getMessage());
    } catch (MessagingException e) {
        log.logError(toString(), "Message error: " + e.getMessage());
    }

    catch (Exception e) {
        log.logError(toString(), "Inexpected error: " + e.getMessage());
    }

    finally {
        if (fileObject != null) {
            try {
                fileObject.close();
            } catch (IOException ex) {
            }
            ;
        }
        sess = null;

    }

    return result;
}

From source file:com.cws.esolutions.core.utils.EmailUtils.java

/**
 * Processes and sends an email message as generated by the requesting
 * application. This method is utilized with a JNDI datasource.
 *
 * @param dataSource - The email message
 * @param authRequired - <code>true</code> if authentication is required, <code>false</code> otherwise
 * @param authList - If authRequired is true, this must be populated with the auth info
 * @return List - The list of email messages in the mailstore
 * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs during processing
 *//*from  w w  w  .  j  a v  a2  s .c o  m*/
public static final synchronized List<EmailMessage> readEmailMessages(final Properties dataSource,
        final boolean authRequired, final List<String> authList) throws MessagingException {
    final String methodName = EmailUtils.CNAME
            + "#readEmailMessages(final Properties dataSource, final boolean authRequired, final List<String> authList) throws MessagingException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("dataSource: {}", dataSource);
        DEBUGGER.debug("authRequired: {}", authRequired);
        DEBUGGER.debug("authList: {}", authList);
    }

    Folder mailFolder = null;
    Session mailSession = null;
    Folder archiveFolder = null;
    List<EmailMessage> emailMessages = null;

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.HOUR, -24);

    final Long TIME_PERIOD = cal.getTimeInMillis();
    final URLName URL_NAME = (authRequired)
            ? new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"),
                    Integer.parseInt(dataSource.getProperty("port")), null, authList.get(0), authList.get(1))
            : new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"),
                    Integer.parseInt(dataSource.getProperty("port")), null, null, null);

    if (DEBUG) {
        DEBUGGER.debug("timePeriod: {}", TIME_PERIOD);
        DEBUGGER.debug("URL_NAME: {}", URL_NAME);
    }

    try {
        // Set up mail session
        mailSession = (authRequired) ? Session.getDefaultInstance(dataSource, new SMTPAuthenticator())
                : Session.getDefaultInstance(dataSource);

        if (DEBUG) {
            DEBUGGER.debug("mailSession: {}", mailSession);
        }

        if (mailSession == null) {
            throw new MessagingException("Unable to configure email services");
        }

        mailSession.setDebug(DEBUG);
        Store mailStore = mailSession.getStore(URL_NAME);
        mailStore.connect();

        if (DEBUG) {
            DEBUGGER.debug("mailStore: {}", mailStore);
        }

        if (!(mailStore.isConnected())) {
            throw new MessagingException("Failed to connect to mail service. Cannot continue.");
        }

        mailFolder = mailStore.getFolder("inbox");
        archiveFolder = mailStore.getFolder("archive");

        if (!(mailFolder.exists())) {
            throw new MessagingException("Requested folder does not exist. Cannot continue.");
        }

        mailFolder.open(Folder.READ_WRITE);

        if ((!(mailFolder.isOpen())) || (!(mailFolder.hasNewMessages()))) {
            throw new MessagingException("Failed to open requested folder. Cannot continue");
        }

        if (!(archiveFolder.exists())) {
            archiveFolder.create(Folder.HOLDS_MESSAGES);
        }

        Message[] mailMessages = mailFolder.getMessages();

        if (mailMessages.length == 0) {
            throw new MessagingException("No messages were found in the provided store.");
        }

        emailMessages = new ArrayList<EmailMessage>();

        for (Message message : mailMessages) {
            if (DEBUG) {
                DEBUGGER.debug("MailMessage: {}", message);
            }

            // validate the message here
            String messageId = message.getHeader("Message-ID")[0];
            Long messageDate = message.getReceivedDate().getTime();

            if (DEBUG) {
                DEBUGGER.debug("messageId: {}", messageId);
                DEBUGGER.debug("messageDate: {}", messageDate);
            }

            // only get emails for the last 24 hours
            // this should prevent us from pulling too
            // many emails
            if (messageDate >= TIME_PERIOD) {
                // process it
                Multipart attachment = (Multipart) message.getContent();
                Map<String, InputStream> attachmentList = new HashMap<String, InputStream>();

                for (int x = 0; x < attachment.getCount(); x++) {
                    BodyPart bodyPart = attachment.getBodyPart(x);

                    if (!(Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()))) {
                        continue;
                    }

                    attachmentList.put(bodyPart.getFileName(), bodyPart.getInputStream());
                }

                List<String> toList = new ArrayList<String>();
                List<String> ccList = new ArrayList<String>();
                List<String> bccList = new ArrayList<String>();
                List<String> fromList = new ArrayList<String>();

                for (Address from : message.getFrom()) {
                    fromList.add(from.toString());
                }

                if ((message.getRecipients(RecipientType.TO) != null)
                        && (message.getRecipients(RecipientType.TO).length != 0)) {
                    for (Address to : message.getRecipients(RecipientType.TO)) {
                        toList.add(to.toString());
                    }
                }

                if ((message.getRecipients(RecipientType.CC) != null)
                        && (message.getRecipients(RecipientType.CC).length != 0)) {
                    for (Address cc : message.getRecipients(RecipientType.CC)) {
                        ccList.add(cc.toString());
                    }
                }

                if ((message.getRecipients(RecipientType.BCC) != null)
                        && (message.getRecipients(RecipientType.BCC).length != 0)) {
                    for (Address bcc : message.getRecipients(RecipientType.BCC)) {
                        bccList.add(bcc.toString());
                    }
                }

                EmailMessage emailMessage = new EmailMessage();
                emailMessage.setMessageTo(toList);
                emailMessage.setMessageCC(ccList);
                emailMessage.setMessageBCC(bccList);
                emailMessage.setEmailAddr(fromList);
                emailMessage.setMessageAttachments(attachmentList);
                emailMessage.setMessageDate(message.getSentDate());
                emailMessage.setMessageSubject(message.getSubject());
                emailMessage.setMessageBody(message.getContent().toString());
                emailMessage.setMessageSources(message.getHeader("Received"));

                if (DEBUG) {
                    DEBUGGER.debug("emailMessage: {}", emailMessage);
                }

                emailMessages.add(emailMessage);

                if (DEBUG) {
                    DEBUGGER.debug("emailMessages: {}", emailMessages);
                }
            }

            // archive it
            archiveFolder.open(Folder.READ_WRITE);

            if (archiveFolder.isOpen()) {
                mailFolder.copyMessages(new Message[] { message }, archiveFolder);
                message.setFlag(Flags.Flag.DELETED, true);
            }
        }
    } catch (IOException iox) {
        throw new MessagingException(iox.getMessage(), iox);
    } catch (MessagingException mex) {
        throw new MessagingException(mex.getMessage(), mex);
    } finally {
        try {
            if ((mailFolder != null) && (mailFolder.isOpen())) {
                mailFolder.close(true);
            }

            if ((archiveFolder != null) && (archiveFolder.isOpen())) {
                archiveFolder.close(false);
            }
        } catch (MessagingException mx) {
            ERROR_RECORDER.error(mx.getMessage(), mx);
        }
    }

    return emailMessages;
}