List of usage examples for javax.mail Flags Flags
public Flags(String flag)
From source file:mover.java
public static void main(String argv[]) { int start = 1; int end = -1; int optind;/* w ww. j a v a 2 s .c om*/ for (optind = 0; optind < argv.length; optind++) { if (argv[optind].equals("-T")) { // protocol protocol = argv[++optind]; } else if (argv[optind].equals("-H")) { // host host = argv[++optind]; } else if (argv[optind].equals("-U")) { // user user = argv[++optind]; } else if (argv[optind].equals("-P")) { // password password = argv[++optind]; } else if (argv[optind].equals("-L")) { url = argv[++optind]; } else if (argv[optind].equals("-s")) { // Source mbox src = argv[++optind]; } else if (argv[optind].equals("-d")) { // Destination mbox dest = argv[++optind]; } else if (argv[optind].equals("-x")) { // Expunge ? expunge = true; } else if (argv[optind].equals("--")) { optind++; break; } else if (argv[optind].startsWith("-")) { System.out.println("Usage: mover [-T protocol] [-H host] [-U user] [-P password] [-L url] [-v]"); System.out.println("\t[-s source mbox] [-d destination mbox] [-x] [msgnum1] [msgnum2]"); System.out.println("\t The -x option => EXPUNGE deleted messages"); System.out.println("\t msgnum1 => start of message-range; msgnum2 => end of message-range"); System.exit(1); } else { break; } } if (optind < argv.length) start = Integer.parseInt(argv[optind++]); // start msg if (optind < argv.length) end = Integer.parseInt(argv[optind++]); // end msg try { // Get a Properties object Properties props = System.getProperties(); // Get a Session object Session session = Session.getInstance(props, null); // Get a Store object Store store = null; if (url != null) { URLName urln = new URLName(url); store = session.getStore(urln); store.connect(); } else { if (protocol != null) store = session.getStore(protocol); else store = session.getStore(); // Connect if (host != null || user != null || password != null) store.connect(host, user, password); else store.connect(); } // Open source Folder Folder folder = store.getFolder(src); if (folder == null || !folder.exists()) { System.out.println("Invalid folder: " + src); System.exit(1); } folder.open(Folder.READ_WRITE); int count = folder.getMessageCount(); if (count == 0) { // No messages in the source folder System.out.println(folder.getName() + " is empty"); // Close folder, store and return folder.close(false); store.close(); return; } // Open destination folder, create if reqd Folder dfolder = store.getFolder(dest); if (!dfolder.exists()) dfolder.create(Folder.HOLDS_MESSAGES); if (end == -1) end = count; // Get the message objects to copy Message[] msgs = folder.getMessages(start, end); System.out.println("Moving " + msgs.length + " messages"); if (msgs.length != 0) { folder.copyMessages(msgs, dfolder); folder.setFlags(msgs, new Flags(Flags.Flag.DELETED), true); // Dump out the Flags of the moved messages, to insure that // all got deleted for (int i = 0; i < msgs.length; i++) { if (!msgs[i].isSet(Flags.Flag.DELETED)) System.out.println("Message # " + msgs[i] + " not deleted"); } } // Close folders and store folder.close(expunge); store.close(); } catch (MessagingException mex) { Exception ex = mex; do { System.out.println(ex.getMessage()); if (ex instanceof MessagingException) ex = ((MessagingException) ex).getNextException(); else ex = null; } while (ex != null); } }
From source file:MainClass.java
public static void main(String argv[]) { int start = 1; int end = -1; int optind;/*w w w . ja v a2 s . c o m*/ for (optind = 0; optind < argv.length; optind++) { if (argv[optind].equals("-T")) { // protocol protocol = argv[++optind]; } else if (argv[optind].equals("-H")) { // host host = argv[++optind]; } else if (argv[optind].equals("-U")) { // user user = argv[++optind]; } else if (argv[optind].equals("-P")) { // password password = argv[++optind]; } else if (argv[optind].equals("-L")) { url = argv[++optind]; } else if (argv[optind].equals("-s")) { // Source mbox src = argv[++optind]; } else if (argv[optind].equals("-d")) { // Destination mbox dest = argv[++optind]; } else if (argv[optind].equals("-x")) { // Expunge ? expunge = true; } else if (argv[optind].equals("--")) { optind++; break; } else if (argv[optind].startsWith("-")) { System.out.println("Usage: mover [-T protocol] [-H host] [-U user] [-P password] [-L url] [-v]"); System.out.println("\t[-s source mbox] [-d destination mbox] [-x] [msgnum1] [msgnum2]"); System.out.println("\t The -x option => EXPUNGE deleted messages"); System.out.println("\t msgnum1 => start of message-range; msgnum2 => end of message-range"); System.exit(1); } else { break; } } if (optind < argv.length) start = Integer.parseInt(argv[optind++]); // start msg if (optind < argv.length) end = Integer.parseInt(argv[optind++]); // end msg try { // Get a Properties object Properties props = System.getProperties(); // Get a Session object Session session = Session.getInstance(props, null); // Get a Store object Store store = null; if (url != null) { URLName urln = new URLName(url); store = session.getStore(urln); store.connect(); } else { if (protocol != null) store = session.getStore(protocol); else store = session.getStore(); // Connect if (host != null || user != null || password != null) store.connect(host, user, password); else store.connect(); } // Open source Folder Folder folder = store.getFolder(src); if (folder == null || !folder.exists()) { System.out.println("Invalid folder: " + folder.getName()); System.exit(1); } folder.open(Folder.READ_WRITE); int count = folder.getMessageCount(); if (count == 0) { // No messages in the source folder System.out.println(folder.getName() + " is empty"); // Close folder, store and return folder.close(false); store.close(); return; } // Open destination folder, create if reqd Folder dfolder = store.getFolder(dest); if (!dfolder.exists()) dfolder.create(Folder.HOLDS_MESSAGES); if (end == -1) end = count; // Get the message objects to copy Message[] msgs = folder.getMessages(start, end); System.out.println("Moving " + msgs.length + " messages"); if (msgs.length != 0) { folder.copyMessages(msgs, dfolder); folder.setFlags(msgs, new Flags(Flags.Flag.DELETED), true); // Dump out the Flags of the moved messages, to insure that // all got deleted for (int i = 0; i < msgs.length; i++) { if (!msgs[i].isSet(Flags.Flag.DELETED)) System.out.println("Message # " + msgs[i] + " not deleted"); } } // Close folders and store folder.close(expunge); store.close(); } catch (MessagingException mex) { Exception ex = mex; do { System.out.println(ex.getMessage()); if (ex instanceof MessagingException) ex = ((MessagingException) ex).getNextException(); else ex = null; } while (ex != null); } }
From source file:nl.ordina.bag.etl.mail.loader.IMAPMutatiesFileLoader.java
@Override public void processMessages() { try {/*from w ww . j ava 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:org.apache.hupa.server.handler.FetchRecentMessagesHandler.java
@Override protected MessageConvertArray getMessagesToConvert(com.sun.mail.imap.IMAPFolder f, FetchRecentMessages action) throws MessagingException { Message[] messages = f.search(new FlagTerm(new Flags(Flag.RECENT), true)); return new MessageConvertArray(messages.length, messages); }
From source file:nl.ordina.bag.etl.mail.loader.POP3MutatiesFileLoader.java
@Override public void processMessages() { try {//from www. 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:org.apache.hupa.server.handler.MoveMessageHandler.java
protected MoveMessageResult executeInternal(MoveMessage action, ExecutionContext context) throws ActionException { User user = getUser();//from w w w. ja va 2 s.c o m try { IMAPStore store = cache.get(user); IMAPFolder folder = (IMAPFolder) store.getFolder(action.getOldFolder().getFullName()); if (folder.isOpen() == false) { folder.open(Folder.READ_WRITE); } Message m = folder.getMessageByUID(action.getMessageUid()); Message[] mArray = new Message[] { m }; folder.copyMessages(mArray, store.getFolder(action.getNewFolder().getFullName())); folder.setFlags(mArray, new Flags(Flags.Flag.DELETED), true); try { folder.expunge(mArray); folder.close(false); } catch (MessagingException e) { // prolly UID expunge is not supported folder.close(true); } return new MoveMessageResult(); } catch (MessagingException e) { logger.error("Error while moving message " + action.getMessageUid() + " from folder " + action.getOldFolder() + " to " + action.getNewFolder(), e); throw new ActionException(e); } }
From source file:org.apache.james.jmap.model.MessageFactoryTest.java
@Test public void emptyMailShouldBeLoadedIntoMessage() throws Exception { MetaDataWithContent testMail = MetaDataWithContent.builder().uid(2).flags(new Flags(Flag.SEEN)).size(0) .internalDate(INTERNAL_DATE).content(new ByteArrayInputStream("".getBytes(Charsets.UTF_8))) .attachments(ImmutableList.of()).mailboxId(MAILBOX_ID).messageId(MessageId.of("test|test|2")) .build();// w w w . j a v a 2s . c om Message testee = messageFactory.fromMetaDataWithContent(testMail); assertThat(testee).extracting(Message::getPreview, Message::getSize, Message::getSubject, Message::getHeaders, Message::getDate).containsExactly("(Empty)", 0L, "", ImmutableMap.of("Date", "Tue, 14 Jul 2015 12:30:42 +0000", "MIME-Version", "1.0"), ZONED_DATE); }
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 .c o 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.accesointeligente.server.robots.ResponseChecker.java
public void connectAndCheck() { if (ApplicationProperties.getProperty("email.server") == null || ApplicationProperties.getProperty("email.user") == null || ApplicationProperties.getProperty("email.password") == null || ApplicationProperties.getProperty("email.folder") == null || ApplicationProperties.getProperty("email.failfolder") == null || ApplicationProperties.getProperty("attachment.directory") == null || ApplicationProperties.getProperty("attachment.baseurl") == null) { logger.error("Properties are not defined!"); return;//from ww w. j a v a 2s . co m } org.hibernate.Session hibernate = null; try { session = Session.getInstance(props, null); store = session.getStore("imaps"); store.connect(ApplicationProperties.getProperty("email.server"), ApplicationProperties.getProperty("email.user"), ApplicationProperties.getProperty("email.password")); Folder failbox = store.getFolder(ApplicationProperties.getProperty("email.failfolder")); Folder inbox = store.getFolder(ApplicationProperties.getProperty("email.folder")); inbox.open(Folder.READ_WRITE); for (Message message : inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false))) { try { logger.info("Sender: " + message.getFrom()[0] + "\tSubject: " + message.getSubject()); remoteIdentifiers = null; messageBody = null; remoteIdentifiers = new HashSet<String>(); if (message.getSubject() != null) { Matcher matcher = pattern.matcher(message.getSubject()); if (matcher.matches()) { remoteIdentifiers.add(formatIdentifier(matcher.group(1), matcher.group(2), Integer.parseInt(matcher.group(3)))); logger.info("remote identifier: " + formatIdentifier(matcher.group(1), matcher.group(2), Integer.parseInt(matcher.group(3)))); } } Object content = message.getContent(); if (content instanceof Multipart) { Multipart mp = (Multipart) message.getContent(); logger.info("Email content type is Multipart, each part of " + mp.getCount() + " will be processed"); for (int i = 0, n = mp.getCount(); i < n; i++) { Part part = mp.getBodyPart(i); logger.info("Part: " + (i + 1) + " of " + mp.getCount()); processPart(part); } } else if (content instanceof String) { logger.info("Email content type is String"); messageBody = (String) content; Matcher matcher; StringTokenizer tokenizer = new StringTokenizer(messageBody); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); matcher = pattern.matcher(token); if (matcher.matches()) { remoteIdentifiers.add(formatIdentifier(matcher.group(1), matcher.group(2), Integer.parseInt(matcher.group(3)))); logger.info("remote identifier: " + formatIdentifier(matcher.group(1), matcher.group(2), Integer.parseInt(matcher.group(3)))); } } } else { logger.info("Email content type isn't String or Multipart"); message.setFlag(Flag.SEEN, false); inbox.copyMessages(new Message[] { message }, failbox); message.setFlag(Flag.DELETED, true); inbox.expunge(); continue; } Boolean requestFound = false; Matcher matcher = htmlPattern.matcher(messageBody); if (matcher.find()) { messageBody = htmlToString(messageBody); } logger.info("Searching for Request Remote Identifier"); for (String remoteIdentifier : remoteIdentifiers) { hibernate = HibernateUtil.getSession(); hibernate.beginTransaction(); Criteria criteria = hibernate.createCriteria(Request.class); criteria.add(Restrictions.eq("remoteIdentifier", remoteIdentifier)); Request request = (Request) criteria.uniqueResult(); hibernate.getTransaction().commit(); if (request != null) { logger.info("Request found for Remote Identifier: " + remoteIdentifier); Response response; // If the attachments haven't been used, use them. Otherwise, copy them. if (!requestFound) { response = createResponse(message.getFrom()[0].toString(), message.getSentDate(), message.getSubject(), messageBody); } else { response = createResponse(message.getFrom()[0].toString(), message.getSentDate(), message.getSubject(), messageBody); } hibernate = HibernateUtil.getSession(); hibernate.beginTransaction(); response.setRequest(request); request.setStatus(RequestStatus.RESPONDED); request.setExpired(RequestExpireType.WITHRESPONSE); request.setResponseDate(new Date()); hibernate.update(request); hibernate.update(response); hibernate.getTransaction().commit(); requestFound = true; } } if (!requestFound) { logger.info("Request not found"); createResponse(message.getFrom()[0].toString(), message.getSentDate(), message.getSubject(), messageBody); message.setFlag(Flag.SEEN, false); inbox.copyMessages(new Message[] { message }, failbox); message.setFlag(Flag.DELETED, true); inbox.expunge(); } } catch (Exception e) { if (hibernate != null && hibernate.isOpen() && hibernate.getTransaction().isActive()) { hibernate.getTransaction().rollback(); } logger.error(e.getMessage(), e); } } } catch (Exception e) { if (hibernate != null && hibernate.isOpen() && hibernate.getTransaction().isActive()) { hibernate.getTransaction().rollback(); } logger.error(e.getMessage(), e); } }
From source file:org.apache.hupa.server.handler.GetMessageDetailsHandler.java
protected MessageDetails exposeMessage(User user, IMAPFolder folder, long uid) throws ActionException { IMAPStore store = null;//from w ww.j a v a2 s . c o m com.sun.mail.imap.IMAPFolder f = null; try { store = cache.get(user); f = (com.sun.mail.imap.IMAPFolder) store.getFolder(folder.getFullName()); if (f.isOpen() == false) { f.open(com.sun.mail.imap.IMAPFolder.READ_WRITE); } MimeMessage message = (MimeMessage) f.getMessageByUID(uid); MessageDetails mDetails = mimeToDetails(message, f.getFullName(), uid); mDetails.setUid(uid); f.setFlags(new Message[] { message }, new Flags(Flag.SEEN), true); return mDetails; } catch (Exception e) { logger.error("Unable to expose msg for user " + user + " in folder " + folder + " with uid " + uid, e); throw new ActionException( "Unable to expose msg for user " + user + " in folder " + folder + " with uid " + uid); } finally { if (f != null && f.isOpen()) { try { f.close(false); } catch (MessagingException e) { // ignore on close } } } }