Example usage for javax.mail Session getStore

List of usage examples for javax.mail Session getStore

Introduction

In this page you can find the example usage for javax.mail Session getStore.

Prototype

public Store getStore(Provider provider) throws NoSuchProviderException 

Source Link

Document

Get an instance of the store specified by Provider.

Usage

From source file:org.apache.usergrid.rest.management.RegistrationIT.java

private Message[] getMessages(String host, String user, String password)
        throws MessagingException, IOException {

    Session session = Session.getDefaultInstance(new Properties());
    Store store = session.getStore("imap");
    store.connect(host, user, password);

    Folder folder = store.getFolder("inbox");
    folder.open(Folder.READ_ONLY);//from   w  w  w  . j a  v  a2 s.c om
    Message[] msgs = folder.getMessages();

    for (Message m : msgs) {
        logger.info("Subject: " + m.getSubject());
        logger.info("Body content 0 " + ((MimeMultipart) m.getContent()).getBodyPart(0).getContent());
        logger.info("Body content 1 " + ((MimeMultipart) m.getContent()).getBodyPart(1).getContent());
    }
    return msgs;
}

From source file:org.alfresco.repo.imap.RemoteLoadTester.java

public void testMailbox() {
    logger.info("Getting folder...");
    long t = System.currentTimeMillis();

    // Create empty properties
    Properties props = new Properties();
    props.setProperty("mail.imap.partialfetch", "false");

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

    Store store = null;//from   w  w  w  . j  a  v  a  2s.  com
    Folder folder = null;
    try {
        // Get the store
        store = session.getStore("imap");
        store.connect(REMOTE_HOST, USER_NAME, USER_PASSWORD);

        // Get folder
        folder = store.getFolder(TEST_FOLDER_NAME);
        folder.open(Folder.READ_ONLY);

        // Get directory
        Message message[] = folder.getMessages();

        for (int i = 0, n = message.length; i < n; i++) {
            message[i].getAllHeaders();

            Address[] from = message[i].getFrom();
            System.out.print(i + ": ");
            if (from != null) {
                System.out.print(message[i].getFrom()[0] + "\t");
            }
            System.out.println(message[i].getSubject());

            Object content = message[i].getContent();
            if (content instanceof MimeMultipart) {
                for (int j = 0, m = ((MimeMultipart) content).getCount(); j < m; j++) {
                    BodyPart part = ((MimeMultipart) content).getBodyPart(j);
                    Object partContent = part.getContent();

                    if (partContent instanceof String) {
                        String body = (String) partContent;
                    } else if (partContent instanceof FilterInputStream) {
                        FilterInputStream fis = (FilterInputStream) partContent;
                        BufferedInputStream bis = new BufferedInputStream(fis);

                        /* while (bis.available() > 0) 
                         {
                            bis.read();
                         }*/
                        byte[] bytes = new byte[524288];
                        while (bis.read(bytes) != -1) {
                        }
                        bis.close();
                        fis.close();
                    }
                }
            }

            int nn = 0;

        }

        t = System.currentTimeMillis() - t;
        logger.info("Time: " + t + " ms (" + t / 1000 + " s)");
        logger.info("Length: " + message.length);

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        fail(e.getMessage());
    } finally {
        // Close connection
        try {
            if (folder != null) {
                folder.close(false);
            }
        } catch (MessagingException e) {
            logger.error(e.getMessage(), e);
            fail(e.getMessage());
        }
        try {
            if (store != null) {
                store.close();
            }
        } catch (MessagingException e) {
            logger.error(e.getMessage(), e);
            fail(e.getMessage());
        }
    }

}

From source file:org.syncope.core.notification.NotificationTest.java

private boolean verifyMail(final String sender, final String subject) {
    LOG.info("Waiting for notification to be sent...");
    try {//  ww w.  j ava2  s  .c o m
        Thread.sleep(10000);
    } catch (InterruptedException e) {
    }

    boolean found = false;
    try {
        Session session = Session.getDefaultInstance(System.getProperties());
        Store store = session.getStore("pop3");
        store.connect(pop3Host, mailAddress, mailPassword);

        Folder inbox = store.getFolder("INBOX");
        assertNotNull(inbox);
        inbox.open(Folder.READ_WRITE);

        Message[] messages = inbox.getMessages();
        for (int i = 0; i < messages.length; i++) {
            if (sender.equals(messages[i].getFrom()[0].toString())
                    && subject.equals(messages[i].getSubject())) {

                found = true;
                messages[i].setFlag(Flag.DELETED, true);
            }
        }
        inbox.close(true);
        store.close();
    } catch (Throwable t) {
        LOG.error("Unexpected exception", t);
        fail("Unexpected exception while fetching e-mail");
    }

    return found;
}

From source file:com.robin.utilities.Utilities.java

/**
 * A utility that waits for a gmail mailbox to receive a new message with
 * according to a given SearchTerm. Only "Not seen" messages are searched,
 * and all match is set as SEEN, but just the first occurrence of the
 * matching message is returned.//from   w ww .jav  a2  s  .  c om
 * @param username the mailbox owner's user name (no @gmail.com required).
 * @param pass the user password protecting this mailbox
 * @param st the SearchTerm built to filter messages
 * @param timeoutMessage the message to show when no such mail found within
 *            timeout
 * @param timeout The maximum amount of time to wait in milliseconds.
 * @return a last from the new messages thats match the st conditions
 */
public EMail waitForMailWithSearchTerm(final String username, final String pass, final SearchTerm st,
        final String timeoutMessage, final long timeout) {
    String host = "imap.gmail.com";
    final long retryTime = 1000;

    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    props.put("mail.imaps.ssl.trust", "*");
    EMail email = null;
    Session session = Session.getDefaultInstance(props, null);
    try {
        Store store = session.getStore("imaps");
        store.connect(host, username, pass);
        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_WRITE);
        FluentWait<Folder> waitForMail = new FluentWait<Folder>(inbox)
                .withTimeout(timeout, TimeUnit.MILLISECONDS).pollingEvery(retryTime, TimeUnit.MILLISECONDS)
                .withMessage(timeoutMessage);
        email = waitForMail.until(new Function<Folder, EMail>() {
            @Override
            public EMail apply(final Folder inbox) {
                EMail email = null;
                FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
                SearchTerm sst = new AndTerm(ft, st);
                try {
                    inbox.getMessageCount();
                    Message[] messages = inbox.search(sst);
                    for (Message message : messages) {
                        message.setFlag(Flag.SEEN, true);
                    }
                    if (messages.length > 0) {
                        return new EMail(messages[0]);
                    }
                } catch (MessagingException e) {
                    Assert.fail(e.getMessage());
                }
                return email;
            }
        });
        inbox.close(false);
        store.close();
    } catch (MessagingException e) {
        Assert.fail(e.getMessage());
    }
    return email;
}

From source file:org.xwiki.contrib.mail.internal.AbstractMailStore.java

/**
 * Creates appropriate javamail Store object.
 * //w  w w .j  a v a 2s. c om
 * @param debug
 * @return
 * @throws NoSuchProviderException
 */
protected Store getJavamailStore(boolean debug) throws NoSuchProviderException {
    Properties props = getStoreProperties();
    Session session = Session.getInstance(props);
    if (debug) {
        session.setDebug(true);
    }

    String url = getProvider() + ":" + getMailSource().getLocation();

    return session.getStore(new URLName(url));
}

From source file:com.openkm.util.MailUtils.java

/**
 * Import messages/*  w ww .  ja  v  a2 s.c  o m*/
 * http://www.jguru.com/faq/view.jsp?EID=26898
 * 
 * == Using Unique Identifier (UIDL) ==
 * Mail server assigns an unique identifier for every email in the same account. You can get as UIDL
 * for every email by MailInfo.UIDL property. To avoid receiving the same email twice, the best way is
 * storing the UIDL of email retrieved to a text file or database. Next time before you retrieve email,
 * compare your local uidl list with remote uidl. If this uidl exists in your local uidl list, don't
 * receive it; otherwise receive it.
 * 
 * == Different property of UIDL in POP3 and IMAP4 ==
 * UIDL is always unique in IMAP4 and it is always an incremental integer. UIDL in POP3 can be any valid
 * asc-ii characters, and an UIDL may be reused by POP3 server if email with this UIDL has been deleted
 * from the server. Hence you are advised to remove the uidl from your local uidl list if that uidl is
 * no longer exist on the POP3 server.
 * 
 * == Remarks ==
 * You should create different local uidl list for different email account, because the uidl is only
 * unique for the same account.
 */
public static String importMessages(String token, MailAccount ma) throws PathNotFoundException,
        ItemExistsException, VirusDetectedException, AccessDeniedException, RepositoryException,
        DatabaseException, UserQuotaExceededException, ExtensionException, AutomationException {
    log.debug("importMessages({}, {})", new Object[] { token, ma });
    Session session = Session.getDefaultInstance(getProperties());
    String exceptionMessage = null;

    try {
        // Open connection
        Store store = session.getStore(ma.getMailProtocol());
        store.connect(ma.getMailHost(), ma.getMailUser(), ma.getMailPassword());

        Folder folder = store.getFolder(ma.getMailFolder());
        folder.open(Folder.READ_WRITE);
        Message messages[] = null;

        if (folder instanceof IMAPFolder) {
            // IMAP folder UIDs begins at 1 and are supposed to be sequential.
            // Each folder has its own UIDs sequence, not is a global one.
            messages = ((IMAPFolder) folder).getMessagesByUID(ma.getMailLastUid() + 1, UIDFolder.LASTUID);
        } else {
            messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
        }

        for (int i = 0; i < messages.length; i++) {
            Message msg = messages[i];
            log.info("======= ======= {} ======= =======", i);
            log.info("Subject: {}", msg.getSubject());
            log.info("From: {}", msg.getFrom());
            log.info("Received: {}", msg.getReceivedDate());
            log.info("Sent: {}", msg.getSentDate());
            com.openkm.bean.Mail mail = messageToMail(msg);

            if (ma.getMailFilters().isEmpty()) {
                log.debug("Import in compatibility mode");
                String mailPath = getUserMailPath(ma.getUser());
                importMail(token, mailPath, true, folder, msg, ma, mail);
            } else {
                for (MailFilter mf : ma.getMailFilters()) {
                    log.debug("MailFilter: {}", mf);

                    if (checkRules(mail, mf.getFilterRules())) {
                        String mailPath = mf.getPath();
                        importMail(token, mailPath, mf.isGrouping(), folder, msg, ma, mail);
                    }
                }
            }

            // Set message as seen
            if (ma.isMailMarkSeen()) {
                msg.setFlag(Flags.Flag.SEEN, true);
            } else {
                msg.setFlag(Flags.Flag.SEEN, false);
            }

            // Delete read mail if requested
            if (ma.isMailMarkDeleted()) {
                msg.setFlag(Flags.Flag.DELETED, true);
            }

            // Set lastUid
            if (folder instanceof IMAPFolder) {
                long msgUid = ((IMAPFolder) folder).getUID(msg);
                log.info("Message UID: {}", msgUid);
                ma.setMailLastUid(msgUid);
                MailAccountDAO.update(ma);
            }
        }

        // Close connection
        log.debug("Expunge: {}", ma.isMailMarkDeleted());
        folder.close(ma.isMailMarkDeleted());
        store.close();
    } catch (NoSuchProviderException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    } catch (MessagingException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    }

    log.debug("importMessages: {}", exceptionMessage);
    return exceptionMessage;
}

From source file:pt.lsts.neptus.comm.iridium.RockBlockIridiumMessenger.java

@Override
public Collection<IridiumMessage> pollMessages(Date timeSince) throws Exception {

    if (askGmailPassword || gmailPassword == null || gmailUsername == null) {
        Pair<String, String> credentials = GuiUtils.askCredentials(ConfigFetch.getSuperParentFrame(),
                "Enter Gmail Credentials", getGmailUsername(), getGmailPassword());
        if (credentials == null)
            return null;
        setGmailUsername(credentials.first());
        setGmailPassword(credentials.second());
        PluginUtils.saveProperties("conf/rockblock.props", this);
        askGmailPassword = false;//from w  ww .  ja  v  a2 s.co  m
    }

    Properties props = new Properties();
    props.put("mail.store.protocol", "imaps");
    ArrayList<IridiumMessage> messages = new ArrayList<>();
    try {
        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");
        store.connect("imap.gmail.com", getGmailUsername(), getGmailPassword());

        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        int numMsgs = inbox.getMessageCount();

        for (int i = numMsgs; i > 0; i--) {
            Message m = inbox.getMessage(i);
            if (m.getReceivedDate().before(timeSince)) {
                break;
            } else {
                MimeMultipart mime = (MimeMultipart) m.getContent();
                for (int j = 0; j < mime.getCount(); j++) {
                    BodyPart p = mime.getBodyPart(j);
                    Matcher matcher = pattern.matcher(p.getContentType());
                    if (matcher.matches()) {
                        InputStream stream = (InputStream) p.getContent();
                        byte[] data = IOUtils.toByteArray(stream);
                        IridiumMessage msg = process(data, matcher.group(1));
                        if (msg != null)
                            messages.add(msg);
                    }
                }
            }
        }
    } catch (NoSuchProviderException ex) {
        ex.printStackTrace();
        System.exit(1);
    } catch (MessagingException ex) {
        ex.printStackTrace();
        System.exit(2);
    }

    return messages;
}

From source file:es.ucm.fdi.dalgs.mailbox.service.MailBoxService.java

/**
 * Returns new messages and fetches details for each message.
 *///  www  . j ava2 s  .c o  m
@Transactional(readOnly = false)
public ResultClass<Boolean> downloadEmails() {

    ResultClass<Boolean> result = new ResultClass<>();
    Properties properties = getServerProperties(protocol, host, port);
    Session session = Session.getDefaultInstance(properties);

    try {

        // connects to the message store
        Store store = session.getStore(protocol);

        store.connect(userName, password);
        // opens the inbox folder
        Folder folderInbox = store.getFolder("INBOX");
        folderInbox.open(Folder.READ_ONLY);
        // fetches new messages from server
        Message[] messages = folderInbox.getMessages();
        for (int i = 0; i < messages.length; i++) {
            Message msg = messages[i];

            String[] idHeaders = msg.getHeader("MESSAGE-ID");
            if (idHeaders != null && idHeaders.length > 0) {

                MessageBox exists = repositoryMailBox.getMessageBox(idHeaders[0]);
                if (exists == null) {

                    MessageBox messageBox = new MessageBox();
                    messageBox.setSubject(msg.getSubject());
                    messageBox.setCode(idHeaders[0]);

                    Address[] fromAddresses = msg.getFrom();
                    String from = InternetAddress.toString(fromAddresses);

                    if (from.startsWith("=?")) {
                        from = MimeUtility.decodeWord(from);
                    }
                    messageBox.setFrom(from);
                    String to = InternetAddress.toString(msg.getRecipients(RecipientType.TO));

                    if (to.startsWith("=?")) {
                        to = MimeUtility.decodeWord(to);
                    }
                    messageBox.setTo(to);

                    String[] replyHeaders = msg.getHeader("References");

                    if (replyHeaders != null && replyHeaders.length > 0) {
                        StringTokenizer tokens = new StringTokenizer(replyHeaders[0]);
                        MessageBox parent = repositoryMailBox.getMessageBox(tokens.nextToken());
                        if (parent != null)
                            parent.addReply(messageBox);
                    }

                    result = parseSubjectAndCreate(messageBox, msg);
                }
            }
        }

        folderInbox.close(false);
        store.close();

        return result;

    } catch (NoSuchProviderException ex) {
        logger.error("No provider for protocol: " + protocol);
        ex.printStackTrace();
    } catch (MessagingException ex) {
        logger.error("Could not connect to the message store");
        ex.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }
    result.setSingleElement(false);
    return result;
}

From source file:com.agiletec.plugins.jpwebmail.aps.system.services.webmail.WebMailManager.java

@Override
public Store initInboxConnection(String username, String password) throws ApsSystemException {
    //Logger log = ApsSystemUtils.getLogger();
    Store store = null;/* w w w  .ja  va2s.c o m*/
    try {
        // Get session
        Session session = this.createSession(false, null, null);
        // Get the store
        store = session.getStore(this.getConfig().getImapProtocol());
        // Connect to store
        //if (log.isLoggable(Level.INFO)) {
        //   log.info("Connection of user " + username);
        //}
        _logger.info("Connection of user " + username);
        //          System.out.print("** tentivo di connessione con protocollo"+this.getConfig().getImapProtocol()+"" +
        //                " a "+this.getConfig().getImapHost()+" ["+this.getConfig().getImapPort()+"]\n");
        store.connect(this.getConfig().getImapHost(), username, password);
    } catch (NoSuchProviderException e) {
        _logger.error("Error opening Provider connection", e);
        //ApsSystemUtils.logThrowable(e, this, "initInboxConnection", "Provider " + this.getConfig().getImapHost() + " non raggiungibile");
        throw new ApsSystemException("Error opening Provider connection", e);
    } catch (Throwable t) {
        _logger.error("Error opening Provider connection", t);
        //ApsSystemUtils.logThrowable(t, this, "initInboxConnection", "Error opening Provider connection");
        throw new ApsSystemException("Error opening Provider connection", t);
    }
    return store;
}

From source file:com.abid_mujtaba.fetchheaders.models.Account.java

public SparseArray<Email> fetchEmails() throws MessagingException // Fetches messages from account and uses them to create an array of Email objects. Catches connection exception and re-throws them up the chain.
{
    Properties props = new Properties();

    props.setProperty("mail.store.protocol", "imaps");
    props.setProperty("mail.imaps.host", mHost);
    props.setProperty("mail.imaps.port", "993");
    props.setProperty("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // Uses SSL to secure communication
    props.setProperty("mail.imaps.socketFactory.fallback", "false");

    Session imapSession = Session.getInstance(props);

    try {//from   w  w w .  j ava  2  s .  c om
        Store store = imapSession.getStore("imaps");

        // Connect to server by sending username and password:
        store.connect(mHost, mUsername, mPassword);

        mInbox = store.getFolder("Inbox");
        mInbox.open(Folder.READ_WRITE); // Open Inbox as read-write since we will be deleting emails later

        mTrash = store.getFolder("Trash");

        if (!mTrash.exists()) {
            mTrash = store.getFolder("[Gmail]/Trash"); // If a folder labelled "Trash" doesn't exist we attempt to check if it is a Gmail account whose trash folder is differently named
            mUsesLabels = true; // Set flag to indicate that this account uses Labels rather than folders a la Gmail

            if (!mTrash.exists()) {
                mTrash = null; // No trash folder found. Emails will be deleted directly
                mUsesLabels = false;
            }
        }

        int num = mInbox.getMessageCount(); // Get number of messages in the Inbox

        if (num > mMaxNumOfEmails) {
            mMessages = mInbox.getMessages(num - mMaxNumOfEmails + 1, num); // Fetch latest mMaxNumOfEmails emails (seen and unseen both). The oldest email is indexed as 1 and so on.
        } else {
            mMessages = mInbox.getMessages();
        }

        FetchProfile fp = new FetchProfile();
        fp.add(IMAPFolder.FetchProfileItem.HEADERS); // Fetch header data
        fp.add(FetchProfile.Item.FLAGS); // Fetch flags

        mInbox.fetch(mMessages, fp);

        // Now that the messages have been fetched using the FetchProfile (that is the necessary information has been fetched with them) we sort the message in reverse chronological order

        Arrays.sort(mMessages, new MessageComparator()); // The sort is accomplished using an instance of a custom comparator that compares messages using DateSent

        mEmails = new SparseArray<Email>();

        for (int ii = 0; ii < mMessages.length; ii++) {
            Email email = new Email(mMessages[ii]);

            mEmails.put(ii, email);
        }

        return mEmails;
    } catch (MessagingException e) {
        Resources.Loge("Exception while attempting to connect to mail server", e);
        throw e;
    } // The two above exceptions are caught by this one if they are not explicitly stated above.
}