List of usage examples for javax.mail Store getFolder
public abstract Folder getFolder(URLName url) throws MessagingException;
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 www .j a v a2s .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:nz.net.orcon.kanban.automation.actions.EmailReceiverAction.java
public void downloadEmails(String mailStoreProtocol, String mailStoreHost, String mailStoreUserName, String mailStorePassword) throws IOException { Session session = getMailStoreSession(mailStoreProtocol, mailStoreHost, mailStoreUserName, mailStorePassword);/*www . j a v a 2 s .c o 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_ONLY); // 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 from = fromAddress[0].toString(); String subject = msg.getSubject(); String toList = parseAddresses(msg.getRecipients(RecipientType.TO)); String ccList = parseAddresses(msg.getRecipients(RecipientType.CC)); String sentDate = msg.getSentDate().toString(); String contentType = msg.getContentType(); String messageContent = ""; if (contentType.contains("text/plain") || contentType.contains("text/html")) { try { Object content = msg.getContent(); if (content != null) { messageContent = content.toString(); } } catch (Exception ex) { messageContent = "[Error downloading content]"; ex.printStackTrace(); } } // print out details of each message System.out.println("Message #" + (i + 1) + ":"); System.out.println("\t From: " + from); System.out.println("\t To: " + toList); System.out.println("\t CC: " + ccList); System.out.println("\t Subject: " + subject); System.out.println("\t Sent Date: " + sentDate); System.out.println("\t Message: " + messageContent); } // disconnect folderInbox.close(false); 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:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java
protected void renameMailbox(final Properties props, final String folderName, final String user, final String password) throws MessagingException { final Store store = Session.getInstance(props).getStore(); store.connect(user, password);/* ww w.ja v a 2 s . c o m*/ checkStoreForTestConnection(store); final Folder f = store.getFolder(folderName); f.renameTo(store.getFolder("renamed_from_" + folderName)); logger.info("Renamed " + f.getFullName()); store.close(); }
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 va 2 s. com*/ 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:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java
protected void deleteMailsFromUserMailbox(final Properties props, final String folderName, final int start, final int deleteCount, final String user, final String password) throws MessagingException { final Store store = Session.getInstance(props).getStore(); store.connect(user, password);/*from www . j ava 2s . c om*/ checkStoreForTestConnection(store); final Folder f = store.getFolder(folderName); f.open(Folder.READ_WRITE); final int msgCount = f.getMessageCount(); final Message[] m = deleteCount == -1 ? f.getMessages() : f.getMessages(start, Math.min(msgCount, deleteCount + start - 1)); int d = 0; for (final Message message : m) { message.setFlag(Flag.DELETED, true); logger.info("Delete msgnum: {} with sid {}", message.getMessageNumber(), message.getSubject()); d++; } f.close(true); logger.info("Deleted " + d + " messages"); store.close(); }
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 w w .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:br.unicamp.cotuca.dpd.pd12.acinet.vagalmail.servlet.Configuracoes.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); if (request.getRequestURI().contains("/pasta")) { String acao = request.getParameter("acao"), url = request.getParameter("url"), novo = request.getParameter("novo"); JSONObject obj = new JSONObject(); if (acao == null || url == null) { obj.put("erro", "Solicitao invlida"); obj.writeJSONString(response.getWriter()); return; }/*from ww w . j ava2 s .co m*/ if ((acao.equals("renomear") || acao.equals("nova")) && novo == null) { obj.put("erro", "Solicitao invlida"); obj.writeJSONString(response.getWriter()); return; } try { Conta conta = (Conta) request.getSession().getAttribute("conta"); Store store = Logar.getImapStore(conta); Folder pasta = null; if (!acao.equals("nova")) { URLName urln = new URLName(url); pasta = store.getFolder(urln); if (pasta.isOpen()) pasta.close(false); } switch (acao) { case "renomear": if (pasta.renameTo(store.getFolder(novo))) { obj.put("sucesso", "Renomeado com sucesso"); } else { obj.put("erro", "Erro ao renomear a pasta"); } break; case "esvaziar": pasta.open(Folder.READ_WRITE); pasta.setFlags(1, pasta.getMessageCount(), new Flags(Flags.Flag.DELETED), true); pasta.expunge(); obj.put("sucesso", "Esvaziado com sucesso"); break; case "excluir": if (pasta.delete(true)) { obj.put("sucesso", "Excludo com sucesso"); } else { obj.put("erro", "Erro ao excluir a pasta"); } break; case "nova": pasta = store.getFolder(novo); if (!pasta.exists()) { if (pasta.create(Folder.HOLDS_FOLDERS | Folder.HOLDS_MESSAGES)) { obj.put("sucesso", "Criado com sucesso"); } else { obj.put("erro", "Erro ao criar a pasta"); } } else { obj.put("erro", "Erro ao criar a pasta"); } break; } } catch (MessagingException ex) { obj.put("erro", "Erro ao processar solicitao"); } obj.writeJSONString(response.getWriter()); return; } String metodo = request.getParameter("acao"); if (metodo == null) { return; } else if (metodo.equals("nova")) { EntityManager em = BD.getEntityManager(); try { em.getTransaction().begin(); Login usuario = Logar.getLogin(request.getSession()); Conta conta = new Conta(); conta.setEmail(request.getParameter("email")); conta.setImapHost(request.getParameter("imapHost")); conta.setImapPort(Integer.parseInt(request.getParameter("imapPort"))); conta.setImapPassword(request.getParameter("imapPassword")); conta.setImapUser(request.getParameter("imapLogin")); conta.setSmtpHost(request.getParameter("smtpHost")); conta.setSmtpPort(Integer.parseInt(request.getParameter("smtpPort"))); conta.setSmtpPassword(request.getParameter("smtpPassword")); conta.setSmtpUser(request.getParameter("smtpLogin")); conta.setIdLogin(usuario); em.persist(conta); em.merge(usuario); em.getTransaction().commit(); em.refresh(conta); em.refresh(usuario); request.setAttribute("mensagem", "sucesso"); } catch (Logar.NaoAutenticadoException | PersistenceException ex) { em.getTransaction().rollback(); request.setAttribute("mensagem", "erro"); } request.getRequestDispatcher("/conf.jsp?metodo=nova").forward(request, response); } else if (metodo.equals("conta")) { EntityManager em = BD.getEntityManager(); try { em.getTransaction().begin(); Conta conta = (Conta) request.getSession().getAttribute("conta"); em.refresh(conta); conta.setEmail(request.getParameter("email")); conta.setImapHost(request.getParameter("imapHost")); conta.setImapPort(Integer.parseInt(request.getParameter("imapPort"))); conta.setImapPassword(request.getParameter("imapPassword")); conta.setImapUser(request.getParameter("imapLogin")); conta.setSmtpHost(request.getParameter("smtpHost")); conta.setSmtpPort(Integer.parseInt(request.getParameter("smtpPort"))); conta.setSmtpPassword(request.getParameter("smtpPassword")); conta.setSmtpUser(request.getParameter("smtpLogin")); em.getTransaction().commit(); request.setAttribute("mensagem", "sucesso"); } catch (PersistenceException ex) { em.getTransaction().rollback(); request.setAttribute("mensagem", "erro"); } request.getRequestDispatcher("/conf.jsp?metodo=conta").forward(request, response); } else if (metodo.equals("senha")) { EntityManager em = BD.getEntityManager(); try { Login usuario = Logar.getLogin(request.getSession()); em.refresh(usuario); String senatu = request.getParameter("senAtu"), novasen = request.getParameter("senNova"), novasen2 = request.getParameter("senNova2"); if (novasen.equals(novasen2) && senatu.equals(usuario.getSenha())) { em.getTransaction().begin(); usuario.setSenha(novasen); em.getTransaction().commit(); request.setAttribute("mensagem", "sucesso"); } else { if (!novasen.equals(novasen2)) request.setAttribute("mensagem", "senneq"); else request.setAttribute("mensagem", "antsen"); } } catch (Logar.NaoAutenticadoException | PersistenceException ex) { em.getTransaction().rollback(); request.setAttribute("mensagem", "erro"); } request.getRequestDispatcher("/conf.jsp?metodo=senha").forward(request, response); } }
From source file:org.opennms.javamail.JavaReadMailer.java
/** * <p>retrieveMessages</p>// w w w .j ava2 s . com * * @param term a {@link javax.mail.search.SearchTerm} object. * @return a {@link java.util.List} object. * @throws org.opennms.javamail.JavaMailerException if any. */ public List<Message> retrieveMessages(SearchTerm term) throws JavaMailerException { Message[] msgs; Folder mailFolder = null; try { Store store = m_session.getStore(m_config.getReadmailHost().getReadmailProtocol().getTransport()); store.connect(m_config.getReadmailHost().getHost(), (int) m_config.getReadmailHost().getPort(), m_config.getUserAuth().getUserName(), m_config.getUserAuth().getPassword()); mailFolder = store.getFolder(m_config.getMailFolder()); mailFolder.open(Folder.READ_WRITE); msgs = mailFolder.search(term); } catch (NoSuchProviderException e) { throw new JavaMailerException( "No provider matching:" + m_config.getReadmailHost().getReadmailProtocol().getTransport() + " from config:" + m_config.getName(), e); } catch (MessagingException e) { throw new JavaMailerException("Problem reading messages from configured mail store", e); } List<Message> msgList = Arrays.asList(msgs); return msgList; }
From source file:org.apache.synapse.transport.mail.MailEchoRawXMLTest.java
private Object getMessage(String requestMsgId) { Session session = Session.getInstance(props, null); session.setDebug(log.isTraceEnabled()); Store store = null; try {//from w ww .j ava 2s .c om store = session.getStore("pop3"); store.connect(username, password); Folder folder = store.getFolder(MailConstants.DEFAULT_FOLDER); folder.open(Folder.READ_WRITE); Message[] msgs = folder.getMessages(); log.debug(msgs.length + " replies in reply mailbox"); for (Message m : msgs) { String[] inReplyTo = m.getHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO); log.debug("Got reply to : " + Arrays.toString(inReplyTo)); if (inReplyTo != null && inReplyTo.length > 0) { for (int j = 0; j < inReplyTo.length; j++) { if (requestMsgId.equals(inReplyTo[j])) { m.setFlag(Flags.Flag.DELETED, true); return m.getContent(); } } } m.setFlag(Flags.Flag.DELETED, true); } folder.close(true); } catch (Exception e) { e.printStackTrace(); } finally { if (store != null) { try { store.close(); } catch (MessagingException ignore) { } store = null; } } return null; }
From source file:com.silverpeas.mailinglist.service.job.TestZimbraConnection.java
@Test public void testOpenImapConnection() { URL url = this.getClass().getClassLoader().getResource("truststore.jks"); String path = url.getPath();/*from ww w. jav a2 s .c o m*/ System.setProperty("javax.net.ssl.trustStore", path); System.setProperty("javax.net.ssl.trustStorePassword", "changeit"); Store mailAccount = null; Folder inbox = null; Session mailSession = Session.getInstance(System.getProperties()); try { mailSession.setDebug(true); mailAccount = mailSession.getStore(props.getProperty("mail.server.protocol")); mailAccount.connect(props.getProperty("mail.server.host"), Integer.parseInt(props.getProperty("mail.server.port")), props.getProperty("mail.server.login"), props.getProperty("mail.server.password")); inbox = mailAccount.getFolder("INBOX"); if (inbox == null) { throw new MessagingException("No POP3 INBOX"); } // -- Open the folder for read write -- inbox.open(Folder.READ_WRITE); // -- Get the message wrappers and process them -- Message[] msgs = inbox.getMessages(); FetchProfile profile = new FetchProfile(); profile.add(FetchProfile.Item.FLAGS); inbox.fetch(msgs, profile); } catch (MessagingException mex) { SilverTrace.error("mailingList", "MessageChecker.checkNewMessages", "mail.processing.error", mex); } catch (Exception mex) { SilverTrace.error("mailingList", "MessageChecker.checkNewMessages", "mail.processing.error", mex); } finally { // -- Close down nicely -- try { if (inbox != null) { inbox.close(false); } if (mailAccount != null) { mailAccount.close(); } } catch (Exception ex2) { SilverTrace.error("mailingList", "MessageChecker.checkNewMessages", "mail.processing.error", ex2); } } }