Exemple #1
0
  public Object getValueAt(int row, int column) {
    try {
      Message message = getMessage(row);
      switch (column) {
        case 0:
          // Answered?
          return (message.isSet(Flags.Flag.ANSWERED) ? "R" : "");

        case 1:
          // From.
          Address[] addresses = message.getFrom();
          if (addresses == null || addresses.length == 0) {
            return "(No sender)";
          }
          // Given "Personal Name <*****@*****.**>", choose "Personal Name" if it's available, and
          // "*****@*****.**" if not.
          InternetAddress address = (InternetAddress) addresses[0];
          String name = address.getPersonal();
          return (name != null) ? name : address.getAddress();

        case 2:
          // Subject.
          String subject = message.getSubject();
          return (subject != null) ? subject : "(No subject)";

        case 3:
          // Date.
          Date date = message.getReceivedDate();
          return (date != null) ? Mailer.dateToIsoString(date) : "Unknown";

        default:
          return "<no-column-" + column + ">";
      }
    } catch (MessagingException ex) {
      ex.printStackTrace();
      return "<error>";
    }
  }
  public static void receberEmailPop() {

    try {

      System.out.println();
      System.out.println("LENDO EMAILS POP...");

      // Verifica qual tipo de provider, se é imap , ou pop/pop3

      ClienteEmailCentralServicoDao clienteEmail = new ClienteEmailCentralServicoDao();
      Message mensagens[] = clienteEmail.getEmail2s();

      MimeMultipart mmp = new MimeMultipart();
      MimeBodyPart mbp1 = new MimeBodyPart();
      MimeBodyPart mbp2 = new MimeBodyPart();

      int contador = 0;
      for (Message message : mensagens) {
        if (!message.isSet(Flags.Flag.SEEN)) {

          String solicitacao = message.getSubject();

          boolean encontrar = solicitacao.matches(".*Solicitação.*");
          /**
           * Verifica se no título do email existe a palavra Solicitação e o número, caso exista,
           * ele vai vincular o email a solicitacao do titulo,
           */
          if (encontrar) {

            encontrar = solicitacao.matches(".*[0-9].*");
            /**
             * Verifica se no título do email possui valor numérico, se possuir, prossegue, senão,
             * encerra
             */
            if (encontrar) {

              /**
               * Retira tudo o que não for numérico, pega os numeros e usa como id da solicitacao de
               * servico
               */
              solicitacao = solicitacao.replaceAll("[^0-9]", "");

              mmp = (MimeMultipart) message.getContent();
              mbp1 = (MimeBodyPart) mmp.getBodyPart(0);
              mbp2 = (MimeBodyPart) mmp.getBodyPart(1);

              System.out.println(
                  "-----------------------------------------------------------------------");
              System.out.println("CONTEÚDO DO EMAIL :" + mbp1.getContent());
              System.out.println("TITULO DO EMAIL : " + message.getSubject());
              System.out.println(
                  "-----------------------------------------------------------------------");
              System.out.println("Contador : " + contador);
              contador++;
              System.out.println();
              System.out.println();
              System.out.println();

              String minutoFormatado = "";

              OcorrenciaSolicitacaoDTO ocorrenciaDto = new OcorrenciaSolicitacaoDTO();
              OcorrenciaSolicitacaoService ocorrenciaService =
                  (OcorrenciaSolicitacaoService)
                      ServiceLocator.getInstance()
                          .getService(OcorrenciaSolicitacaoService.class, null);
              ocorrenciaDto.setIdSolicitacaoServico(Integer.parseInt(solicitacao));
              Calendar calendar = Calendar.getInstance();
              int hora = calendar.get(Calendar.HOUR_OF_DAY);
              int minuto = calendar.get(Calendar.MINUTE);
              ocorrenciaDto.setDataregistro(UtilDatas.getSqlDate(new java.util.Date()));
              if (minuto < 10) {
                minutoFormatado = "0" + String.valueOf(minuto);
                ocorrenciaDto.setHoraregistro(hora + ":" + minuto);
              } else {
                ocorrenciaDto.setHoraregistro(hora + ":" + minuto);
              }

              ocorrenciaDto.setRegistradopor("Email - Automatico");
              ocorrenciaDto.setDescricao(message.getSubject().toString());
              ocorrenciaDto.setOcorrencia(mbp1.getContent().toString());
              SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
              java.sql.Date dataFormatada = UtilDatas.getSqlDate(message.getReceivedDate());
              ocorrenciaDto.setDataregistro(UtilDatas.getSqlDate(new java.util.Date()));
              String data = UtilDatas.formatHoraFormatadaHHMMSSStr(message.getReceivedDate());
              ocorrenciaService.create(ocorrenciaDto);
            }
          }
        }
      }

      System.out.println("THREAD FINALIZADA!!!---------------------");

    } catch (Exception e) {
      System.out.println("###########################################");
      System.out.println("Erro ao executar a Thread");
      System.out.println("###########################################");
      e.printStackTrace();
    }
  }
  public ClienteEmailCentralServicoDTO readMessage(
      DocumentHTML document,
      HttpServletRequest request,
      HttpServletResponse response,
      String messageId)
      throws Exception {
    ClienteEmailCentralServicoDTO clienteEmailCentralServicoDto =
        new ClienteEmailCentralServicoDTO();
    clienteEmailCentralServicoDto.setResultSucess(true);

    try {
      if (CONEXAO_EMAIL_SERVIDOR.equals("")
          || CONEXAO_EMAIL_PROVIDER.equals("")
          || CONEXAO_EMAIL_CAIXA.equals("")
          || CONEXAO_EMAIL_SENHA.equals("")
          || CONEXAO_EMAIL_PASTA.equals("")) {
        clienteEmailCentralServicoDto.setResultSucess(false);
        clienteEmailCentralServicoDto.setResultMessage(
            UtilI18N.internacionaliza(
                request, "clienteEmailCentralServico.problemasRealizarleituraEmailsParametros"));
      } else {
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", CONEXAO_EMAIL_PROVIDER);

        props.setProperty("mail.imaps.auth.plain.disable", "true");
        props.setProperty("mail.imaps.ssl.trust", "*");
        // props.setProperty("mail.debug", "true");

        if (!CONEXAO_EMAIL_PORTA.equals(""))
          props.setProperty("mail." + CONEXAO_EMAIL_PROVIDER + ".port", CONEXAO_EMAIL_PORTA);

        Session session = Session.getInstance(props, null);
        Store store = session.getStore();
        store.connect(CONEXAO_EMAIL_SERVIDOR, CONEXAO_EMAIL_CAIXA, CONEXAO_EMAIL_SENHA);

        Folder inbox = store.getFolder(CONEXAO_EMAIL_PASTA);
        inbox.open(Folder.READ_WRITE);

        SearchTerm searchTerm = new MessageIDTerm(messageId);
        Message[] messages = inbox.search(searchTerm);

        if (messages != null && messages.length > 0) {
          ArrayList<ClienteEmailCentralServicoMessagesDTO> emailMessages =
              new ArrayList<ClienteEmailCentralServicoMessagesDTO>();
          for (Message message : messages) {
            ClienteEmailCentralServicoMessagesDTO clienteEmailMessagesDto =
                new ClienteEmailCentralServicoMessagesDTO();

            MimeMessage m = (MimeMessage) inbox.getMessage(message.getMessageNumber());
            clienteEmailMessagesDto.setMessageId(m.getMessageID());
            clienteEmailMessagesDto.setMessageNumber(message.getMessageNumber());

            Address[] in = message.getFrom();
            clienteEmailMessagesDto.setMessageEmail(
                (in == null ? null : ((InternetAddress) in[0]).getAddress()));

            clienteEmailMessagesDto.setMessageSubject(message.getSubject());
            clienteEmailMessagesDto.setMessageReceivedDate(message.getReceivedDate());
            clienteEmailMessagesDto.setSeen(message.isSet(Flags.Flag.SEEN));

            Object objRef = message.getContent();
            String content = "";

            if (!(objRef instanceof Multipart)) {
              content = (String) message.getContent();
            } else {
              Multipart mp = (Multipart) message.getContent();
              BodyPart bp = mp.getBodyPart(0);

              content = getContent(bp);
            }

            if (content != null) {
              // content = content.replaceAll("(\r\n|\r|\n)", "<br />");
              content = StringEscapeUtils.escapeEcmaScript(content);

              clienteEmailMessagesDto.setMessageContent(content);
            }

            emailMessages.add(clienteEmailMessagesDto);
          }

          clienteEmailCentralServicoDto.setEmailMessages(emailMessages);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      clienteEmailCentralServicoDto.setResultSucess(false);
      clienteEmailCentralServicoDto.setResultMessage(
          UtilI18N.internacionaliza(
              request, "clienteEmailCentralServico.problemasRealizarleituraEmails"));
    }

    return clienteEmailCentralServicoDto;
  }
  /**
   * {@inheritDoc}
   *
   * @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);
        }
      }
    }
  }
Exemple #5
0
 /**
  * Check if the given message is claimed by any of the registred importers and handle it.
  *
  * @param message the message to import or to ignore
  * @param aCurrentAccount the currently selected account in the JGnucashEditor
  * @param aWritableModel the gnucash-file
  * @return true if the message has been handled successfully
  * @throws MessagingException in case of mail- issues
  * @throws IOException in case of io-issues
  * @throws JAXBException in case of XML-issues with the plugins
  */
 private boolean importMessage(
     final Message message,
     final GnucashWritableAccount aCurrentAccount,
     final GnucashWritableFile aWritableModel)
     throws MessagingException, IOException, JAXBException {
   LOG.fine("=========================================");
   if (message.isSet(Flag.DELETED)) {
     return false;
   }
   LOG.info("Message: " + message.getSubject());
   LOG.info("disposition: " + message.getDisposition());
   LOG.info("contentType: " + message.getContentType());
   if (message.isSet(Flag.SEEN)) {
     LOG.info("Flagged: SEEN");
   }
   if (message.isSet(Flag.DRAFT)) {
     LOG.info("Flagged: DRAFT");
   }
   if (message.isSet(Flag.ANSWERED)) {
     LOG.info("Flagged: ANSWERED");
   }
   if (message.isSet(Flag.USER)) {
     LOG.info("Flagged: USER");
   }
   if (message.isSet(Flag.FLAGGED)) {
     LOG.info("Flagged: FLAGGED");
   }
   if (message.isSet(Flag.RECENT)) {
     LOG.info("Flagged: RECENT");
   }
   if (message.isSet(Flag.DELETED)) {
     LOG.info("Flagged: DELETED");
   }
   Flag[] systemFlags = message.getFlags().getSystemFlags();
   for (Flag flag : systemFlags) {
     LOG.info("system-flag: " + flag.toString());
   }
   String[] userFlags = message.getFlags().getUserFlags();
   for (String flag : userFlags) {
     LOG.info("user-flag: " + flag);
   }
   Object readTextContent = message.getContent();
   Object content = readTextContent;
   LOG.info("content: " + content.getClass().getName());
   //        if (message instanceof MimeMessage) {
   //            MimeMessage msg = (MimeMessage) message;
   //            msg.getco
   //        }
   if (content instanceof InputStream
       && message.getContentType().toLowerCase().contains("multipart")) {
     content = new MimeMultipart(new InputStreamDataSource(message));
   }
   if (content instanceof InputStream
       && message.getContentType().toLowerCase().startsWith("text")) {
     // call plugins for text/plain -messages too
     Collection<MailImportHandler> mailHandlers = PluginMain.getMailHandlers();
     LOG.fine("handling as text/* via our #" + mailHandlers.size() + " plugins...");
     for (MailImportHandler mailImportHandler : mailHandlers) {
       LOG.fine(
           "handling as text/* via our #"
               + mailHandlers.size()
               + " plugins...trying "
               + mailImportHandler.getClass().getName());
       if (mailImportHandler.handleTextMail(
           aWritableModel, message.getSubject(), message, readTextContent(message))) {
         return true;
       }
     }
   }
   if (content instanceof Multipart) {
     Multipart mp = (Multipart) content;
     // call plugins
     Collection<MailImportHandler> mailHandlers = PluginMain.getMailHandlers();
     LOG.fine("handling as multipart via our #" + mailHandlers.size() + " plugins...");
     for (MailImportHandler mailImportHandler : mailHandlers) {
       LOG.fine(
           "handling as text/* via our #"
               + mailHandlers.size()
               + " plugins...trying "
               + mailImportHandler.getClass().getName());
       if (mailImportHandler.handleMultiPartMail(
           aWritableModel, message.getSubject(), message, mp)) {
         return true;
       }
     }
     //            for (int i = 0; i < mp.getCount(); i++) {
     //                Part part = mp.getBodyPart(i);
     //                String disposition = part.getDisposition();
     //                if (disposition == null) {
     //                    continue;
     //                }
     //                if (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE))
     // {
     //                    LOG.info("\tAttachment: " + part.getFileName() + " of type " +
     // part.getContentType());
     //                    //part.getInputStream()
     //                }
     //            }
   }
   return false;
 }