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.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 {/* w  ww . j  a  v a 2 s  . c  o  m*/
        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.
}

From source file:ru.retbansk.utils.scheduled.impl.ReadEmailAndConvertToXmlSpringImpl.java

/**
 * Loads email properties, reads email messages, 
 * converts their multipart bodies into string,
 * send error emails if message doesn't contain valid report and at last returns a reversed Set of the Valid Reports
 * <p><b> deletes messages//from w ww.j  a  v  a 2 s .c  om
 * @see #readEmail()
 * @see #convertToXml(HashSet)
 * @see ru.retbansk.utils.scheduled.ReplyManager
 * @return HashSet<DayReport> of the Valid Day Reports
 */
@Override
public HashSet<DayReport> readEmail() throws Exception {

    Properties prop = loadProperties();
    String host = prop.getProperty("host");
    String user = prop.getProperty("user");
    String password = prop.getProperty("password");
    path = prop.getProperty("path");

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

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    // Get a Store object that implements the specified protocol.
    Store store = session.getStore("pop3");

    // Connect to the current host using the specified username and
    // password.
    store.connect(host, user, password);

    // Create a Folder object corresponding to the given name.
    Folder folder = store.getFolder("inbox");

    // Open the Folder.
    folder.open(Folder.READ_WRITE);
    HashSet<DayReport> dayReportSet = new HashSet<DayReport>();
    try {

        // Getting messages from the folder
        Message[] message = folder.getMessages();
        // Reversing the order in the array with the use of Set to make the last one final
        Collections.reverse(Arrays.asList(message));

        // Reading messages.
        String body;
        for (int i = 0; i < message.length; i++) {
            DayReport dayReport = null;
            dayReport = new DayReport();
            dayReport.setPersonId(((InternetAddress) message[i].getFrom()[0]).getAddress());
            Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+3"));
            calendar.setTime(message[i].getSentDate());
            dayReport.setCalendar(calendar);
            dayReport.setSubject(message[i].getSubject());
            List<TaskReport> reportList = null;

            //Release the string from email message body
            body = "";
            Object content = message[i].getContent();
            if (content instanceof java.lang.String) {
                body = (String) content;
            } else if (content instanceof Multipart) {
                Multipart mp = (Multipart) content;

                for (int j = 0; j < mp.getCount(); j++) {
                    Part part = mp.getBodyPart(j);

                    String disposition = part.getDisposition();

                    if (disposition == null) {
                        MimeBodyPart mbp = (MimeBodyPart) part;
                        if (mbp.isMimeType("text/plain")) {
                            body += (String) mbp.getContent();
                        }
                    } else if ((disposition != null)
                            && (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE))) {
                        MimeBodyPart mbp = (MimeBodyPart) part;
                        if (mbp.isMimeType("text/plain")) {
                            body += (String) mbp.getContent();
                        }
                    }
                }
            }

            //Put the string (body of email message) and get list of valid reports else send error
            reportList = new ArrayList<TaskReport>();
            reportList = giveValidReports(body, message[i].getSentDate());
            //Check for valid day report. To be valid it should have size of reportList > 0.
            if (reportList.size() > 0) {
                // adding valid ones to Set
                dayReport.setReportList(reportList);
                dayReportSet.add(dayReport);
            } else {
                // This message doesn't have valid reports. Sending an error reply.
                logger.info("Invalid Day Report detected. Sending an error reply");
                ReplyManager man = new ReplyManagerSimpleImpl();
                man.sendError(dayReport);
            }
            // Delete message
            message[i].setFlag(Flags.Flag.DELETED, true);
        }

    } finally {
        // true tells the mail server to expunge deleted messages.
        folder.close(true);
        store.close();
    }

    return dayReportSet;
}

From source file:com.intranet.intr.inbox.EmpControllerInbox.java

public int todosCorreosNum(String name) {
    int num = 0;//from   w  w w  . j  av a2s  . com
    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    try {
        users u = usuarioService.getByLogin(name);
        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");
        store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna());
        System.out.println("ola" + store);
        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        Message msg[] = inbox.getMessages();
        System.out.println("MAILS: " + msg.length);
        System.out.println(" " + msg.length);
        num = msg.length;
    } catch (Exception ex) {
        System.out.println(ex.toString());
    }
    return num;
}

From source file:com.intranet.intr.inbox.EmpControllerInbox.java

public int numCorreosNOL(String name) {
    int numMensa = 0;
    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    try {/*  w ww.j  a va 2 s. c o  m*/
        users u = usuarioService.getByLogin(name);

        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");

        store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna());

        System.out.println("ola" + store);

        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);

        Message msg[] = inbox.search(ft);
        System.out.println("MAILS: " + msg.length);
        System.out.println(" " + msg.length);
        numMensa = msg.length;
    } catch (Exception ex) {
    }
    return numMensa;
}

From source file:com.intranet.intr.inbox.EmpControllerInbox.java

@RequestMapping(value = "/EajaxtestNoL", method = RequestMethod.GET)
public @ResponseBody String ajaxtestNoL(Principal principal) {
    String name = principal.getName();
    String result = "";
    try {/*from  ww  w.j av  a  2s. c  om*/
        users u = usuarioService.getByLogin(name);

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

        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");

        store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna());

        System.out.println("ola" + store);

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

        FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
        Calendar fecha3 = Calendar.getInstance();
        fecha3.roll(Calendar.MONTH, false);
        Message msg[] = inbox.search(new ReceivedDateTerm(ComparisonTerm.GT, fecha3.getTime()));
        //Message msg[] = inbox.search(ft);
        System.out.println("MAILS: " + msg.length);
        for (Message message : msg) {
            try {
                /*System.out.println("DATE: "+message.getSentDate().toString());
                System.out.println("FROM: "+message.getFrom()[0].toString());            
                System.out.println("SUBJECT: "+message.getSubject().toString());
                System.out.println("CONTENT: "+message.getContent().toString());
                System.out.println("******************************************");
                */result = result + "<li>" + "<a href='#' class='clearfix'>" + "<span class='msg-body'>"
                        + "<span class='msg-title'>" + "<span class='blue'>" + message.getFrom()[0].toString()
                        + "</span>" +

                        message.getSubject().toString() + "</span>" +

                        "</span>" + "</a>" + "</li> ";
            } catch (Exception e) {
                // TODO Auto-generated catch block
                System.out.println("No Information");
            }
        }

    } catch (Exception ex) {
    }

    return result;
}

From source file:com.intranet.intr.inbox.EmpControllerInbox.java

public correoNoLeidos ltaRecibidos2(String name, int num) {
    correoNoLeidos lta = new correoNoLeidos();
    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    try {//from ww w  .  j av a  2s.  com
        users u = usuarioService.getByLogin(name);
        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");

        store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna());

        System.out.println("ola" + store);

        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        Calendar fecha3 = Calendar.getInstance();
        fecha3.roll(Calendar.MONTH, false);
        Message msg[] = inbox.search(new ReceivedDateTerm(ComparisonTerm.GT, fecha3.getTime()));
        //Message msg[] = inbox.getMessages();
        System.out.println("MAILS: " + msg.length);
        for (Message message : msg) {
            try {
                if (num == message.getMessageNumber()) {
                    //message.setFlag(Flags.Flag.SEEN, true);
                    lta.setNum(message.getMessageNumber());
                    lta.setFecha(message.getSentDate().toString());
                    lta.setDe(message.getFrom()[0].toString());
                    lta.setAsunto(message.getSubject().toString());
                    correoNoLeidos co = new correoNoLeidos();
                    List<String> arc = new ArrayList<String>();
                    List<String> rar = new ArrayList<String>();
                    correoNoLeidos cc = analizaParteDeMensaje2(co, arc, rar, message);
                    lta.setImagenes(cc.getImagenes());
                    lta.setRar(cc.getRar());
                    lta.setContenido(cc.getContenido());
                    String cont = "";

                    String contenido = "";

                    //lta.setContenido(analizaParteDeMensaje2(message));
                }
            } catch (Exception e) {
                System.out.println("No Information");
            }

        }
    } catch (MessagingException e) {
        System.out.println(e.toString());
    }

    return lta;
}

From source file:ch.entwine.weblounge.bridge.mail.MailAggregator.java

/**
 * {@inheritDoc}//  ww  w.  ja  v a  2  s.  c o m
 * 
 * @see ch.entwine.weblounge.common.scheduler.JobWorker#execute(java.lang.String,
 *      java.util.Dictionary)
 */
public void execute(String name, Dictionary<String, Serializable> ctx) throws JobException {

    Site site = (Site) ctx.get(Site.class.getName());

    // Make sure the site is ready to accept content
    if (site.getContentRepository().isReadOnly()) {
        logger.warn("Unable to publish e-mail messages to site '{}': repository is read only", site);
        return;
    }

    WritableContentRepository repository = (WritableContentRepository) site.getContentRepository();

    // Extract the configuration from the job properties
    String provider = (String) ctx.get(OPT_PROVIDER);
    Account account = null;
    try {
        if (StringUtils.isBlank(provider)) {
            provider = DEFAULT_PROVIDER;
        }
        account = new Account(ctx);
    } catch (IllegalArgumentException e) {
        throw new JobException(this, e);
    }

    // Connect to the server
    Properties sessionProperties = new Properties();
    Session session = Session.getDefaultInstance(sessionProperties, null);
    Store store = null;
    Folder inbox = null;

    try {

        // Connect to the server
        try {
            store = session.getStore(provider);
            store.connect(account.getHost(), account.getLogin(), account.getPassword());
        } catch (NoSuchProviderException e) {
            throw new JobException(this, "Unable to connect using unknown e-mail provider '" + provider + "'",
                    e);
        } catch (MessagingException e) {
            throw new JobException(this, "Error connecting to " + provider + " account " + account, e);
        }

        // Open the account's inbox
        try {
            inbox = store.getFolder(INBOX);
            if (inbox == null)
                throw new JobException(this, "No inbox found at " + account);
            inbox.open(Folder.READ_WRITE);
        } catch (MessagingException e) {
            throw new JobException(this, "Error connecting to inbox at " + account, e);
        }

        // Get the messages from the server
        try {
            for (Message message : inbox.getMessages()) {
                if (!message.isSet(Flag.SEEN)) {
                    try {
                        Page page = aggregate(message, site);
                        message.setFlag(Flag.DELETED, true);
                        repository.put(page, true);
                        logger.info("E-Mail message published at {}", page.getURI());
                    } catch (Exception e) {
                        logger.info("E-Mail message discarded: {}", e.getMessage());
                        message.setFlag(Flag.SEEN, true);
                        // TODO: Reply to sender if the "from" field exists
                    }
                }
            }
        } catch (MessagingException e) {
            throw new JobException(this, "Error loading e-mail messages from inbox", e);
        }

        // Close the connection
        // but don't remove the messages from the server
    } finally {
        if (inbox != null) {
            try {
                inbox.close(true);
            } catch (MessagingException e) {
                throw new JobException(this, "Error closing inbox", e);
            }
        }
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException e) {
                throw new JobException(this, "Error closing connection to e-mail server", e);
            }
        }
    }

}

From source file:com.intranet.intr.inbox.SupControllerInbox.java

@RequestMapping(value = "/ajaxtestNoL", method = RequestMethod.GET)
public @ResponseBody String ajaxtestNoL(Principal principal) {
    String name = principal.getName();
    String result = "";
    try {/*from   www  .  ja  v  a  2  s.  c o m*/
        users u = usuarioService.getByLogin(name);

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

        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");

        store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna());

        System.out.println("ola" + store);

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

        FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
        Calendar fecha3 = Calendar.getInstance();
        fecha3.roll(Calendar.MONTH, false);
        Message msg[] = inbox.search(new ReceivedDateTerm(ComparisonTerm.GT, fecha3.getTime()));
        //Message msg[] = inbox.search(ft);
        System.out.println("MAILS: " + msg.length);
        for (Message message : msg) {
            try {
                /*System.out.println("DATE: "+message.getSentDate().toString());
                System.out.println("FROM: "+message.getFrom()[0].toString());            
                System.out.println("SUBJECT: "+message.getSubject().toString());
                System.out.println("CONTENT: "+message.getContent().toString());
                System.out.println("******************************************");
                */result = result + "<li>" + "<a href='#' class='clearfix'>" + "<span class='msg-body'>"
                        + "<span class='msg-title'>" + "<span class='blue'>" + message.getFrom()[0].toString()
                        + "</span>" +

                        message.getSubject().toString() + "</span>" +

                        "</span>" + "</a>" + "</li> ";
            } catch (Exception e) {
                // TODO Auto-generated catch block
                System.out.println("No Information");
            }
        }

    } catch (Exception ex) {
    }

    return result;
}

From source file:org.campware.cream.modules.scheduledjobs.Pop3Job.java

private void doReceiveMessages() throws Exception {

    log.debug("Checking mail ");

    String host = Turbine.getConfiguration().getString("mail.pop3.host");
    String username = Turbine.getConfiguration().getString("mail.pop3.user");
    String password = Turbine.getConfiguration().getString("mail.pop3.password");

    // Create empty properties
    Properties props = new Properties();

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

    // Get the store
    Store store = session.getStore("pop3");

    // Connect to store
    store.connect(host, username, password);

    // Get folder
    Folder folder = store.getFolder("INBOX");

    // Open read-only
    folder.open(Folder.READ_WRITE);//ww w.  j  av a2  s . c o  m

    // Get attributes & flags for all messages
    //
    Message[] messages = folder.getMessages();
    FetchProfile fp = new FetchProfile();
    fp.add(FetchProfile.Item.ENVELOPE);
    fp.add(FetchProfile.Item.FLAGS);
    fp.add("X-Mailer");
    folder.fetch(messages, fp);

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

        log.debug("Retrieving message " + i);

        // Process each message
        //
        InboxEvent entry = new InboxEvent();
        Address fromAddress = new InternetAddress();
        String from = new String();
        String name = new String();
        String email = new String();
        String replyTo = new String();
        String subject = new String();
        String content = new String();
        Date sentDate = new Date();
        int emailformat = 10;

        Message m = messages[i];

        // and now, handle the content
        Object o = m.getContent();

        // find content type
        if (m.isMimeType("text/plain")) {
            content = "<PRE style=\"font-size: 12px;\">" + (String) o + "</PRE>";
            emailformat = 10;
        } else if (m.isMimeType("text/html")) {
            content = (String) o;
            emailformat = 20;
        } else if (m.isMimeType("text/*")) {
            content = (String) o;
            emailformat = 30;
        } else if (m.isMimeType("multipart/alternative")) {
            try {
                content = handleAlternative(o, content);
                emailformat = 20;
            } catch (Exception ex) {
                content = "Problem with the message format. Messssage has left on the email server.";
                emailformat = 50;
                log.error(ex.getMessage(), ex);
            }
        } else if (m.isMimeType("multipart/*")) {
            try {
                content = handleMulitipart(o, content, entry);
                emailformat = 40;
            } catch (Exception ex) {
                content = "Problem with the message format. Messssage has left on the email server.";
                emailformat = 50;
                log.error(ex.getMessage(), ex);
            }
        } else {
            content = "Problem with the message format. Messssage has left on the email server.";
            emailformat = 50;
            log.debug("Could not handle properly");
        }

        email = ((InternetAddress) m.getFrom()[0]).getAddress();
        name = ((InternetAddress) m.getFrom()[0]).getPersonal();
        replyTo = ((InternetAddress) m.getReplyTo()[0]).getAddress();
        sentDate = m.getSentDate();
        subject = m.getSubject();

        log.debug("Got message " + email + " " + name + " " + subject + " " + content);

        Criteria contcrit = new Criteria();
        contcrit.add(ContactPeer.EMAIL, (Object) email, Criteria.EQUAL);
        if (ContactPeer.doSelect(contcrit).size() > 0) {
            log.debug("From known contact");
            Contact myContact = (Contact) ContactPeer.doSelect(contcrit).get(0);
            entry.setCustomerId(myContact.getCustomerId());
            entry.setContactId(myContact.getContactId());
        } else {

            // find if customer exists
            Criteria criteria = new Criteria();
            criteria.add(CustomerPeer.EMAIL, (Object) email, Criteria.EQUAL);
            if (CustomerPeer.doSelect(criteria).size() > 0) {
                log.debug("From known customer");
                Customer myDistrib = (Customer) CustomerPeer.doSelect(criteria).get(0);
                entry.setCustomerId(myDistrib.getCustomerId());
            }

        }

        entry.setInboxEventCode(getTempCode());
        entry.setEventType(10);
        entry.setEventChannel(10);
        entry.setEmailFormat(emailformat);
        entry.setSubject(subject);
        entry.setSenderEmail(email);
        entry.setSenderName(name);
        entry.setSenderReplyTo(replyTo);
        entry.setSentTime(sentDate);
        entry.setBody(content);
        entry.setIssuedDate(new Date());
        entry.setCreatedBy("system");
        entry.setCreated(new Date());
        entry.setModifiedBy("system");
        entry.setModified(new Date());

        Connection conn = Transaction.begin(InboxEventPeer.DATABASE_NAME);
        boolean success = false;
        try {
            entry.save(conn);
            entry.setInboxEventCode(getRowCode("IE", entry.getInboxEventId()));
            entry.save(conn);
            Transaction.commit(conn);
            success = true;
        } finally {
            log.debug("Succcessfully stored in db: " + success);
            if (!success)
                Transaction.safeRollback(conn);
        }

        if (emailformat != 50) {
            m.setFlag(Flags.Flag.DELETED, true);
        }
    }

    // Close pop3 connection
    folder.close(true);
    store.close();

}

From source file:com.naryx.tagfusion.cfm.mail.cfPOP3.java

private Store openConnection(cfSession _Session) throws cfmRunTimeException {
    String server = getDynamic(_Session, "SERVER").getString();
    boolean secure = getSecure(_Session);
    int port = getPort(_Session, secure);
    String user = getDynamic(_Session, "USERNAME").getString();
    String pass = getDynamic(_Session, "PASSWORD").getString();

    Properties props = new Properties();
    String protocol = "pop3";
    if (secure) {
        protocol = "pop3s";
    }// w  ww  .j a va  2s .  co m

    props.put("mail.transport.protocol", protocol);
    props.put("mail." + protocol + ".port", String.valueOf(port));

    // This is the fix for bug NA#3156
    props.put("mail.mime.address.strict", "false");

    // With WebLogic Server 8.1sp4 and an IMAIL server, we're seeing that sometimes the first
    // attempt to connect after messages have been deleted fails with either a MessagingException 
    // of "Connection reset" or an AuthenticationFailedException of "EOF on socket".  To work
    // around this let's try 3 attempts to connect before giving up.
    for (int numAttempts = 1; numAttempts < 4; numAttempts++) {
        try {
            Session session = Session.getInstance(props);
            Store mailStore = session.getStore(protocol);
            mailStore.connect(server, user, pass);
            return mailStore;
        } catch (Exception E) {
            if (numAttempts == 3)
                throw newRunTimeException(E.getMessage());
        }
    }

    // The code in the for loop should either return or throw an exception
    // so this code should never get hit.
    return null;
}