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(String host, String user, String password) throws MessagingException 

Source Link

Document

Connect to the specified address.

Usage

From source file:com.hs.mail.web.controller.FetchAccountFormController.java

private Store connect(String userName, String password) throws MessagingException {
    Session session = Session.getInstance(System.getProperties(), null);
    Store store = session.getStore("imap");
    store.connect("localhost", userName, password);
    return store;
}

From source file:nl.ordina.bag.etl.mail.loader.IMAPMutatiesFileLoader.java

@Override
public void processMessages() {
    try {/*from www  .  j av  a  2  s .c  om*/
        Session session = Session.getDefaultInstance(new Properties(), null);
        Store store = session.getStore(protocol);
        if (port == 0)
            store.connect(host, username, password);
        else
            store.connect(host, port, username, password);

        Folder folder = store.getFolder(folderName);
        if (folder == null)
            throw new RuntimeException("Folder " + folderName + " not found!");
        folder.open(Folder.READ_WRITE);

        try {
            FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
            Message messages[] = folder.search(ft);
            for (Message message : messages) {
                messageHandler.handle(message);
                message.setFlags(new Flags(Flags.Flag.SEEN), true);
            }
        } finally {
            folder.close(true);
            store.close();
        }
    } catch (MessagingException | IOException | JAXBException e) {
        throw new ProcessingException(e);
    }
}

From source file:nl.ordina.bag.etl.mail.loader.POP3MutatiesFileLoader.java

@Override
public void processMessages() {
    try {/*from w w w  .ja v a  2  s  .c om*/
        Session session = Session.getDefaultInstance(new Properties(), null);
        Store store = session.getStore(protocol);
        if (port == 0)
            store.connect(host, username, password);
        else
            store.connect(host, port, username, password);

        Folder folder = store.getFolder(folderName);
        if (folder == null)
            throw new RuntimeException("Folder " + folderName + " not found!");
        folder.open(Folder.READ_WRITE);

        try {
            Message[] messages = folder.getMessages();
            for (Message message : messages) {
                backup(message);
                messageHandler.handle(message);
                message.setFlags(new Flags(Flags.Flag.DELETED), true);
            }
        } finally {
            folder.close(true);
            store.close();
        }
    } catch (MessagingException | IOException | JAXBException e) {
        throw new ProcessingException(e);
    }
}

From source file:net.sourceforge.subsonic.backend.service.EmailSession.java

public Folder getFolder(String name) throws Exception {
    Store store = session.getStore("imaps");
    store.connect(IMAP_MAIL_SERVER, USER, password);
    Folder folder = store.getFolder(name);
    folder.open(Folder.READ_ONLY);/*ww w. j a va2s .c  om*/
    return folder;
}

From source file:com.yfiton.notifiers.email.EmailNotifierTest.java

private boolean checkEmailReception(String subject, String host, String username, String password)
        throws MessagingException {
    Properties properties = new Properties();
    properties.put("mail.store.protocol", "imaps");
    Session session = Session.getInstance(properties);

    Store store = null;

    try {/*from w  ww  . ja  v a  2 s  . c  o  m*/
        store = session.getStore("imaps");
        store.connect(host, username, password);

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

        Message[] messages = inbox.getMessages();

        for (Message message : messages) {
            if (message.getSubject().equals(subject)) {
                message.setFlag(Flags.Flag.DELETED, true);
                return true;
            }
        }

        inbox.close(true);
    } finally {
        try {
            if (store != null) {
                store.close();
            }
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    return false;
}

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

/**
 * Import messages// w  w  w  .j a  va 2s .  com
 * 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 + ": " + msg.getFrom()[0] + " " + msg.getSubject() + " " + msg.getContentType());
            log.info("Received: " + msg.getReceivedDate());
            log.info("Sent: " + msg.getSentDate());
            log.debug("{} -> {} - {}", new Object[] { i, msg.getSubject(), msg.getReceivedDate() });
            com.ikon.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:com.treesbearfruit.icloudnotes.NotesSaver.java

public NotesSaver(String username, String password, String j, String wheretosave) throws Exception {

    // Get system properties
    Properties props = System.getProperties();

    Session session = Session.getDefaultInstance(props);

    // Get the store
    Store store = session.getStore("imaps");
    String noteFolderLabel = "";

    if (j.toLowerCase().equals("apple")) {
        noteFolderLabel = "Notes";
        store.connect("imap.mail.me.com", username, password); // username without @icloud.com
    } else if (j.toLowerCase().equals("google")) {
        noteFolderLabel = "Notes";
        store.connect("imap.gmail.com", username, password);
    } else {/*  w w w  .  j a v  a 2 s  .c o m*/
        throw new Exception("Notesprovider not implemented!");
    }

    String timestamp = new java.text.SimpleDateFormat("dd_MM_yyyy_hh_mm_ss").format(new Date());
    String backup_directory = wheretosave + (wheretosave.endsWith(File.separator) ? "" : File.separator)
            + noteFolderLabel + "_" + timestamp + File.separator;

    // saves main folder
    save(store, backup_directory, noteFolderLabel);

    // folder..s   
    Folder mainnotefolder = store.getFolder(noteFolderLabel);
    System.out.println("found " + mainnotefolder.list().length + " note folders");
    Folder[] f = mainnotefolder.list();
    for (Folder fd : f) {
        String backup_directory_i = backup_directory + fd.getName();
        save(store, backup_directory_i, noteFolderLabel + "/" + fd.getName());
    }

    // Close connection
    store.close();
}

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

/**
 * Test IMAP connection/*  ww w  . j  a  v  a 2s  .c o m*/
 */
public static void testConnection(MailAccount ma) throws IOException {
    log.debug("testConnection({})", ma);
    Session session = Session.getDefaultInstance(getProperties());
    Store store = null;
    Folder folder = null;

    try {
        store = session.getStore(ma.getMailProtocol());
        store.connect(ma.getMailHost(), ma.getMailUser(), ma.getMailPassword());
        folder = store.getFolder(ma.getMailFolder());
        folder.open(Folder.READ_WRITE);
        folder.close(false);
    } catch (NoSuchProviderException e) {
        throw new IOException(e.getMessage());
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    } finally {
        // Try to close folder
        if (folder != null && folder.isOpen()) {
            try {
                folder.close(false);
            } catch (MessagingException e) {
                throw new IOException(e.getMessage());
            }
        }

        // Try to close store
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException e) {
                throw new IOException(e.getMessage());
            }
        }
    }

    log.debug("testConnection: void");
}

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

public void testListSequence() {
    System.out.println(String.format("Connecting to remote server '%s'", REMOTE_HOST));
    Properties props = System.getProperties();
    props.setProperty("mail.imap.partialfetch", "false");
    Session session = Session.getDefaultInstance(props, null);

    Store store = null;
    long startTime = 0;
    long endTime = 0;
    try {/*from   w  w  w . j  a v a  2s . c  o m*/
        store = session.getStore("imap");
        store.connect(REMOTE_HOST, ADMIN_USER_NAME, ADMIN_USER_NAME);
        Folder[] folders = null;

        startTime = System.currentTimeMillis();
        folders = store.getDefaultFolder().list("");
        endTime = System.currentTimeMillis();
        System.out.println(String.format("LIST '', folders.length = %d, execTime = %d sec", folders.length,
                (endTime - startTime) / 1000));

        startTime = System.currentTimeMillis();
        folders = store.getDefaultFolder().list("*");
        endTime = System.currentTimeMillis();
        System.out.println(String.format("LIST *, folders.length = %d, execTime = %d sec", folders.length,
                (endTime - startTime) / 1000));

        startTime = System.currentTimeMillis();
        folders = store.getDefaultFolder().listSubscribed("*");
        endTime = System.currentTimeMillis();
        System.out.println(String.format("LSUB *, folders.length = %d, execTime = %d sec", folders.length,
                (endTime - startTime) / 1000));

        startTime = System.currentTimeMillis();
        for (Folder folder : folders) {
            folder.getMessageCount();
            //Folder f = store.getFolder(folder.getFullName());
        }
        endTime = System.currentTimeMillis();
        System.out.println(String.format("Folders Loop, folders.length = %d, execTime = %d sec", folders.length,
                (endTime - startTime) / 1000));

    } catch (NoSuchProviderException e) {
        e.printStackTrace();
    } catch (MessagingException e) {
        e.printStackTrace();
    } finally {
        try {
            store.close();
        } catch (MessagingException e) {
            System.err.println(e.getMessage());
        }
    }
}

From source file:com.crawlersick.nettool.GetattchmentFromMail1.java

public boolean fetchmailforattch() throws IOException, MessagingException {
    boolean fetchtest = false;

    Properties props = new Properties();
    props.setProperty("mail.store.protocol", "imaps");

    try {// w  w w . j a v  a 2s .  c o m
        Session session = Session.getInstance(props, null);
        Store store = session.getStore();
        store.connect(IMapHost, MailId, MailPassword);
        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_ONLY);
        totalmailcount = inbox.getMessageCount();

        Message msg = null;
        for (int i = totalmailcount; i > 0; i--) {
            fromadd = "";
            msg = inbox.getMessage(i);
            Address[] in = msg.getFrom();
            for (Address address : in) {
                fromadd = address.toString() + fromadd;
                //System.out.println("FROM:" + address.toString());
            }
            if (fromadd.matches("admin@cronmailservice.appspotmail.com") && msg.getSubject().matches(
                    "ThanksToTsukuba_World-on-my-shoulders-as-I-run-back-to-this-8-Mile-Road_cronmailservice"))
                break;
        }

        if (fromadd.equals("'")) {
            log.log(Level.SEVERE, "Error: no related mail found!" + this.MailId);
            return fetchtest;
        }

        //    Multipart mp = (Multipart) msg.getContent();
        //  BodyPart bp = mp.getBodyPart(0);
        sentdate = msg.getSentDate().toString();

        subject = msg.getSubject();

        Content = msg.getContent().toString();

        log.log(Level.INFO, Content);
        log.log(Level.INFO, sentdate);
        localIntent.putExtra("213123", "Got Server latest update at : " + sentdate + " , Reading the Data...");
        LocalBroadcastManager.getInstance(myis).sendBroadcast(localIntent);

        Multipart multipart = (Multipart) msg.getContent();
        for (int i = 0; i < multipart.getCount(); i++) {
            BodyPart bodyPart = multipart.getBodyPart(i);
            if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && (bodyPart.getFileName() == null
                    || !bodyPart.getFileName().equals("dataforvgendwithudp.gzip"))) {
                continue; // dealing with attachments only
            }
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            InputStream is = bodyPart.getInputStream();
            //validvgbinary = IOUtils.toByteArray(is);
            int nRead;
            byte[] data = new byte[5000000];

            while ((nRead = is.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }

            buffer.flush();

            validvgbinary = buffer.toByteArray();
            break;
        }

        fetchtest = true;
    } catch (Exception mex) {
        mex.printStackTrace();

    }

    return fetchtest;
}