Example usage for javax.mail Store connect

List of usage examples for javax.mail Store connect

Introduction

In this page you can find the example usage for javax.mail Store connect.

Prototype

public void connect() throws MessagingException 

Source Link

Document

A generic connect method that takes no parameters.

Usage

From source file:com.trivago.mail.pigeon.mail.MailFacade.java

public void readBounceAccount() throws MessagingException {
    Session session = Session.getDefaultInstance(Settings.create().getConfiguration().getProperties("mail.*"));
    Store store = session.getStore("pop3");

    store.connect();

    // Get folder
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_ONLY);/*from   w  w w  . j  a  v  a2s.c  o  m*/

    if (folder.hasNewMessages()) {
        // Get directory
        Message message[] = folder.getMessages();
        BounceFacade bounceFacade = new BounceFacade();

        for (Message msg : message) {
            boolean isBounce = bounceFacade.processBounce(msg);
            if (isBounce) {
                msg.setFlag(Flags.Flag.SEEN, true);
                msg.saveChanges();
            }
        }
    }

}

From source file:org.apache.axis2.transport.mail.MailClient.java

public int checkInbox(int mode) throws MessagingException, IOException {
    int numMessages = 0;

    if (mode == 0) {
        return 0;
    }/*w w w.  j  ava  2  s  .c o  m*/

    boolean show = (mode & SHOW_MESSAGES) > 0;
    boolean clear = (mode & CLEAR_MESSAGES) > 0;
    String action = (show ? "Show" : "") + ((show && clear) ? " and " : "") + (clear ? "Clear" : "");

    log.info(action + " INBOX for " + from);

    Store store = session.getStore();

    store.connect();

    Folder root = store.getDefaultFolder();
    Folder inbox = root.getFolder("inbox");

    inbox.open(Folder.READ_WRITE);

    Message[] msgs = inbox.getMessages();

    numMessages = msgs.length;

    if ((msgs.length == 0) && show) {
        log.info("No messages in inbox");
    }

    for (int i = 0; i < msgs.length; i++) {
        MimeMessage msg = (MimeMessage) msgs[i];

        if (show) {
            log.info("    From: " + msg.getFrom()[0]);
            log.info(" Subject: " + msg.getSubject());
            log.info(" Content: " + msg.getContent());
        }

        if (clear) {
            msg.setFlag(Flags.Flag.DELETED, true);
        }
    }

    inbox.close(true);
    store.close();

    return numMessages;
}

From source file:com.google.code.rptm.mailarchive.DefaultMailingListArchive.java

public void retrieveMessages(String mailingList, YearMonth month, MimeMessageProcessor processor,
        MailingListArchiveEventListener eventListener) throws MailingListArchiveException {
    Session session = Session.getDefaultInstance(new Properties());
    try {/*ww w . ja  v a2  s .  com*/
        Store store = session.getStore(new URLName("mstor:" + getMboxFile(mailingList, month, eventListener)));
        store.connect();
        try {
            Folder folder = store.getDefaultFolder();
            folder.open(Folder.READ_ONLY);
            for (Message msg : folder.getMessages()) {
                if (!processor.processMessage((MimeMessage) msg)) {
                    break;
                }
            }
        } finally {
            store.close();
        }
    } catch (MessagingException ex) {
        throw new MailingListArchiveException("JavaMail exception: " + ex.getMessage(), ex);
    } catch (IOException ex) {
        throw new MailingListArchiveException("I/O exception: " + ex.getMessage(), ex);
    }
}

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

/**
 * {@inheritDoc}//  w  ww  . j  a  va  2  s .com
 * 
 * @throws MessagingException
 * @see org.xwiki.contrib.mail.IMailReader#readFromStore(java.lang.String)
 */
public Message read(String folder, String messageid) throws MessagingException {
    Store store = getJavamailStore();
    store.connect();

    Folder mailFolder = store.getDefaultFolder().getFolder(folder);
    mailFolder.open(Folder.READ_ONLY);
    Message[] messages = mailFolder.search(new MessageIDTerm(messageid));
    mailFolder.close(false);
    store.close();
    if (messages.length > 0) {
        return messages[0];
    }
    return null;
}

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

/**
 * {@inheritDoc}/*from  w ww  .java2  s  .c  om*/
 * 
 * @see org.xwiki.contrib.mail.IMailReader#readFromStore(java.lang.String)
 */
@Override
public List<Message> read(String folder, boolean onlyUnred, int max) throws MessagingException {
    Store store = getJavamailStore();
    store.connect();
    Folder mailFolder = store.getDefaultFolder();
    if (StringUtils.isNotEmpty(folder)) {
        mailFolder = mailFolder.getFolder(folder);
    }
    mailFolder.open(Folder.READ_WRITE);
    Message[] msgsArray = mailFolder.getMessages();
    if (max > 0 && msgsArray.length > max) {
        msgsArray = (Message[]) ArrayUtils.subarray(msgsArray, 0, max);
    }
    List<Message> messages = new ArrayList<Message>(Arrays.asList(msgsArray));
    mailFolder.close(false);
    store.close();
    return messages;
}

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

/**
 * ????//from ww  w . ja v  a2s  .c  o  m
 *
 * @param callback
 *            ??1???
 * @throws Exception
 */
public void execute(ReceiveIterationCallback callback) throws Exception {
    final Session session = useDefaultSession
            ? Session.getDefaultInstance(properties.getProperties(), properties.getAuthenticator())
            : Session.getInstance(properties.getProperties(), properties.getAuthenticator());
    session.setDebug(isDebug);

    Store store = null;
    Folder folder = null;
    try {
        store = session.getStore(properties.getProtocol());
        store.connect();

        folder = store.getFolder(folderName);
        folder.open(readonly ? Folder.READ_ONLY : Folder.READ_WRITE);

        final Message messages[] = folder.getMessages();
        for (Message message : messages) {
            MessageLoader loader = new MessageLoader(message, !readonly);
            boolean isContinued = callback.iterate(loader);
            if (!readonly && loader.isDeleted()) {
                message.setFlag(Flags.Flag.DELETED, loader.isDeleted());
            }
            if (!isContinued) {
                break;
            }
        }
    } finally {
        if (folder != null) {
            try {
                folder.close(!readonly);
            } catch (MessagingException e) {
                System.out.println(e);
            }
        }
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException e) {
                System.out.println(e);
            }
        }
    }
}

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

/**
 * @param folder//from   w  ww  .j  av a 2 s .c o  m
 * @param message
 * @throws MessagingException
 */
public void write(String folder, Message message) throws MessagingException {
    // getLogger().info("Delivering " + message + " to " + this.location + " / " + folder);

    final Store store = getJavamailStore(true);
    store.connect();
    final Folder mailFolder = store.getDefaultFolder().getFolder(folder);
    if (!mailFolder.exists()) {
        mailFolder.create(Folder.HOLDS_MESSAGES);
    }
    mailFolder.open(Folder.READ_WRITE);
    // If message is already archived, do nothing
    final Message existingMessage = read(folder, message.getHeader("Message-ID")[0]);
    if (existingMessage == null) {
        // The Store Provider may add some headers to the message to store, but IMAPMessage are read-only
        // So we clone the message before storing it
        final MimeMessage cloned = cloneEmail(message);
        mailFolder.appendMessages(new Message[] { cloned });
    }

    mailFolder.close(true);
    store.close();
}

From source file:edu.stanford.muse.email.MboxEmailStore.java

public Folder openFolderWithoutCount(Store s, String fname) throws MessagingException {
    if (fname == null)
        fname = "INBOX";

    // ignore the store coming in, we need a new session and store
    // for each folder

    Session session = Session.getInstance(mstorProps, null);
    session.setDebug(DEBUG);/* ww w.java 2s  .  co  m*/

    // Get a Store object
    Store store = session.getStore(new URLName("mstor:" + fname));
    store.connect();

    //This is the root folder in the namespace provided
    //see http://docs.oracle.com/javaee/5/api/javax/mail/Store.html#getDefaultFolder%28%29
    Folder folder = store.getDefaultFolder();
    if (folder == null)
        throw new RuntimeException("Invalid folder: " + fname);

    log.info("Opening folder " + Util.blurPath(fname) + " in r/o mode...");
    try {
        folder.open(Folder.READ_ONLY);
    } catch (MessagingException me) {
        folder = null;
    }

    return folder;
}

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

@Override
public ArrayList<FolderItem> getFolderTree() throws MessagingException {
    getLogger().debug("getFolderTree");

    assert (getMailSource() != null);

    ArrayList<FolderItem> folderItems = new ArrayList<FolderItem>();

    Store store = getJavamailStore();
    store.connect();
    Folder defaultFolder = store.getDefaultFolder();
    FolderItem item = new FolderItem();
    item.setIndex(0);//from w w w  .  jav  a  2  s  .  com
    item.setLevel(0);
    item.setName(defaultFolder.getName());
    item.setFullName(defaultFolder.getFullName());
    if ((defaultFolder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) {
        item.setMessageCount(defaultFolder.getMessageCount());
        item.setUnreadMessageCount(defaultFolder.getUnreadMessageCount());
        item.setNewMessageCount(defaultFolder.getNewMessageCount());
    }
    Folder[] folders = defaultFolder.list("*");
    if (ArrayUtils.isEmpty(folders)) {
        folders = defaultFolder.list();
    }

    getLogger().debug("Found folders {}", ArrayUtils.toString(folders));
    int index = 1;
    int level = 1;
    // TODO not really managing folders here, just listing them
    for (Folder folder : folders) {

        item = new FolderItem();
        item.setIndex(index);
        item.setLevel(level);
        item.setName(folder.getName());
        item.setFullName(folder.getFullName());
        if ((folder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) {
            item.setMessageCount(folder.getMessageCount());
            item.setUnreadMessageCount(folder.getUnreadMessageCount());
            item.setNewMessageCount(folder.getNewMessageCount());
            folderItems.add(item);
        }
    }

    store.close();

    return folderItems;

}

From source file:org.webguitoolkit.messagebox.mail.MailChannel.java

/**
 * //w w  w . j  a v  a 2s . c om
 */
@Override
public List<IMessage> receive(boolean clear) {
    List<IMessage> result = new ArrayList<IMessage>();

    try {
        String user = properties.getProperty("pop3.login.user");
        String password = properties.getProperty("pop3.login.password");

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

        Properties pop3Props = new Properties();

        pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
        pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
        pop3Props.setProperty("mail.pop3.port", properties.getProperty("pop3.port"));
        pop3Props.setProperty("mail.pop3.socketFactory.port", properties.getProperty("pop3.port"));

        URLName url = new URLName("pop3", properties.getProperty("pop3.host"),
                Integer.valueOf(properties.getProperty("pop3.port")), "", user, password);

        Session session = Session.getInstance(pop3Props, null);
        Store store = new POP3SSLStore(session, url);
        store.connect();

        // Open the Folder
        Folder folder = store.getDefaultFolder();
        folder = folder.getFolder("INBOX");

        if (folder == null) {
            throw new RuntimeException("Invalid folder INBOX");
        }

        // try to open read/write and if that fails try read-only
        try {
            folder.open(Folder.READ_WRITE);
        } catch (MessagingException ex) {
            folder.open(Folder.READ_ONLY);
        }

        int count = folder.getMessageCount();
        // Message numbers start at 1
        for (int i = 1; i <= count; i++) {
            // Get a message by its sequence number
            Message m = folder.getMessage(i);
            Address[] from = m.getFrom();
            String type = from[0].getType();

            IMessage message = new MailMessage(from[0].toString(), this, m.getSubject(), getContent(m));

            result.add(message);

            // delete message ?
            if (clear)
                m.setFlag(Flags.Flag.DELETED, true);
        }

        // "true" actually deletes flagged messages from folder
        folder.close(clear);
        store.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return result;
}