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);
    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();
  }
Пример #2
0
 public boolean isMessageTooOld(Account account, Message message, String context)
     throws MessagingException {
   if (message.getSentDate() == null) {
     log.warn(
         String.format("we have a message with no sent date for %s, allowing message", context));
     return false;
   } else if (account.getRegister_time() == null) {
     log.warn(
         String.format(
             "we are process an account with no register time. this behavior is not understood yet %s, we will accept this message",
             context));
     return false;
   } else {
     boolean messageTooOld =
         (System.currentTimeMillis() - message.getSentDate().getTime())
             > 1000l * 60 * 60 * 24 * emailDaysCutoff;
     if (messageTooOld) {
       log.warn(
           String.format(
               "msgNum=%d, message is too old, sentDate=%s, discarding, for %s",
               message.getMessageNumber(), message.getSentDate(), context));
     }
     return messageTooOld;
   }
 }
 public CustomProperties getMessageProperties(Message message, String prefix, CustomProperties p)
     throws MessagingException, IOException {
   CustomProperties envVars = new CustomProperties();
   String msgSubject = stringify(message.getSubject());
   envVars.put(prefix + "subject", msgSubject);
   envVars.put(prefix + "from", stringify(message.getFrom()));
   envVars.put(prefix + "replyTo", stringify(message.getReplyTo()));
   envVars.put(prefix + "flags", stringify(message.getFlags()));
   envVars.put(prefix + "folder", stringify(message.getFolder()));
   envVars.put(prefix + "messageNumber", stringify(message.getMessageNumber()));
   envVars.put(prefix + "receivedDate", stringify(message.getReceivedDate()));
   envVars.put(prefix + "sentDate", stringify(message.getSentDate()));
   envVars.put(prefix + "headers", stringify(message.getAllHeaders()));
   envVars.put(prefix + "content", stringify(message));
   envVars.put(prefix + "contentType", stringify(message.getContentType()));
   envVars.put(prefix + "recipients", stringify(message.getAllRecipients()));
   // add parameters from email content
   final CustomProperties properties = CustomProperties.read(getText(message));
   envVars.putAll(properties);
   //            envVars.put(prefix + "emailParams", stringify(properties.getMap(), "=", "&"));
   // add "jobTrigger"
   if (p.has(subjectContains)) {
     String subject = p.get(subjectContains);
     // normalise strings, find index, then get text after it
     int idx = msgSubject.toLowerCase().indexOf(subject.toLowerCase());
     int beginIndex = idx + subject.length();
     if (idx > -1 && beginIndex < msgSubject.length()) {
       envVars.put(prefix + "jobTrigger", msgSubject.substring(beginIndex).trim());
     }
   }
   return envVars;
 }
Пример #4
0
  /**
   * @param msgId
   * @param destFolder
   * @throws Exception
   */
  public void moveEmail(Long msgId, String destFolder) throws Exception {
    ProtocolFactory factory = new ProtocolFactory(profile, auth, handler);
    ImapProtocolImpl fromProtocol = (ImapProtocolImpl) factory.getImap(folder);
    ImapProtocolImpl destProtocol = (ImapProtocolImpl) factory.getImap(destFolder);
    Folder from = fromProtocol.getFolder();
    Folder dest = null;

    try {
      Message msg = fromProtocol.getMessage(msgId.intValue());
      if (msg != null) {
        // because of the buggy imap servers lost the connection after getMessage
        // we need to check if the folder is open or not.
        // (Do not use uw-imapd, it sucks!!!)
        from = fromProtocol.getFolder();
        dest = destProtocol.getFolder();
        from.copyMessages(new Message[] {msg}, dest);
        // deleteMessages(new int[] {msg.getMessageNumber()});
        flagAsDeleted(new int[] {msg.getMessageNumber()});
      }
    } catch (IndexOutOfBoundsException e) {
      log.debug("Index kaçtı. Moving message to folder : " + destFolder + " failed.", e);
    } catch (Exception e) {
      log.warn("Moving message to folder : " + destFolder + " failed.", e);
    }
  }
  @Before
  public void before() throws KettleException {
    MockitoAnnotations.initMocks(this);

    Mockito.when(parentJob.getLogLevel()).thenReturn(LogLevel.BASIC);
    entry.setParentJob(parentJob);
    entry.setSaveMessage(true);

    Mockito.when(message.getMessageNumber()).thenReturn(1);
    Mockito.when(mailConn.getMessage()).thenReturn(message);

    Mockito.doNothing().when(mailConn).openFolder(Mockito.anyBoolean());
    Mockito.doNothing().when(mailConn).openFolder(Mockito.anyString(), Mockito.anyBoolean());

    Mockito.when(mailConn.getMessagesCount()).thenReturn(1);
  }
Пример #6
0
  /**
   * It so happens Gmail sends us sent messages as well as received once
   *
   * @param account
   * @param message
   * @return
   * @throws Exception
   */
  protected boolean isSentMessage(Account account, Message message) throws Exception {
    MessageParser parser = new MessageParser();

    if (EmailUtil.isFromSameAsAccount(account, message)) {
      String to = parser.parseMsgAddress(message, "TO", true);
      String cc = parser.parseMsgAddress(message, "CC", true);

      if (!to.contains(account.getName()) && !cc.contains(account.getName())) {
        log.warn(
            String.format(
                "msgNum=%d, message is 'sent' not 'received' discarding, for %s",
                message.getMessageNumber(), account.getName()));
        return true;
      }
    }

    return false;
  }
Пример #7
0
  /**
   * Creates a Mail
   *
   * @param inboxHelper
   * @param message
   * @param mUId
   * @return
   * @throws FolderClosedException
   * @throws MessagingException
   * @throws IOException
   */
  public static RawMail createMail(Message message) throws FolderClosedException {
    try {
      // fill the message objects with messagedata
      String[] fromInfo = MailUtils.getFromInfo(message.getFrom());

      if (fromInfo[0] == null || fromInfo[0].isEmpty()) {
        fromInfo = MailUtils.getFromInfo(message.getReplyTo());
      }
      if (fromInfo[0] == null || fromInfo[0].isEmpty()) {
        String[] returnPath = message.getHeader("Return-Path");
        if (returnPath.length > 0) {
          fromInfo[0] = returnPath[0].trim();
          if (fromInfo[0].charAt(0) == '<') fromInfo[0].substring(1);
          if (fromInfo[0].charAt(fromInfo[0].length() - 1) == '>')
            fromInfo[0].substring(0, fromInfo[0].length() - 2);
        }
      }

      String mFromAddress = (fromInfo[0] != null) ? fromInfo[0] : "";
      RawMail mail = new RawMail();
      // Note: Mail ids are generated based on contents - do not set an id

      String mSubject = message.getSubject();
      mail.setSubject(mSubject);
      mail.setFrom(new EmailAddress(mFromAddress, fromInfo[1]));
      mail.setCreated(new Date());

      // Prevent evil mail servers from sending from the future
      Date now = new Date();
      Date sentDate = message.getSentDate();
      Date recDate = message.getReceivedDate();

      if (sentDate == null || now.before(sentDate)) sentDate = new Date();
      if (recDate == null || now.before(recDate)) recDate = new Date();

      mail.setSentDate(sentDate);
      mail.setRecievedDate(recDate);

      mail.setServerId(String.valueOf(message.getMessageNumber()));

      try {
        mail.setBody(MailUtils.getBody(message));
      } catch (Throwable ex) {
        System.out.println("Failed when reading mail body");
      }

      // Headers
      Enumeration<?> allHeaders = message.getAllHeaders();
      HashMap<String, String> mailHeaders = new HashMap<String, String>();
      while (allHeaders.hasMoreElements()) {
        Header header = (Header) allHeaders.nextElement();
        mailHeaders.put(header.getName(), header.getValue());
      }
      mail.setHeaders(mailHeaders);

      try {
        mail.setRecipients(MailUtils.getRecipients(Message.RecipientType.TO, message));
      } catch (Throwable ex) {
        System.out.println("Throwable during setRecipients");
      }
      try {
        mail.setRecipients(MailUtils.getRecipients(Message.RecipientType.CC, message));
      } catch (Throwable ex) {
        System.out.println("Throwable during setRecipients");
      }
      try {
        mail.setRecipients(MailUtils.getRecipients(Message.RecipientType.BCC, message));
      } catch (Throwable ex) {
        System.out.println("Throwable during setRecipients");
      }
      return mail;
    } catch (FolderClosedException ex) {
      throw ex;
    } catch (Throwable ex) {
      System.out.println("Could not read mail");
    }
    return null;
  }
Пример #8
0
 /** Returns the message number. */
 public String getNum() {
   return (Integer.toString(message.getMessageNumber()));
 }
  public ClienteEmailCentralServicoDTO getMessages(
      DocumentHTML document, HttpServletRequest request, HttpServletResponse response)
      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);

        Message[] messages = inbox.getMessages();

        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));
            clienteEmailMessagesDto.setSeen(true);

            emailMessages.add(clienteEmailMessagesDto);
          }

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

    return clienteEmailCentralServicoDto;
  }
  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;
  }
  public ClienteEmailCentralServicoDTO getMessagesByLimitAndNoRequest(
      DocumentHTML document, HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    EmailSolicitacaoServicoService emailSolicitacaoServicoService =
        (EmailSolicitacaoServicoService)
            ServiceLocator.getInstance()
                .getService(
                    EmailSolicitacaoServicoService.class, WebUtil.getUsuarioSistema(request));
    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);

        Message[] messages = inbox.getMessages();

        if (messages != null && messages.length > 0) {
          ArrayUtils.reverse(messages);

          Integer limiteEmails = 10;

          try {
            limiteEmails = Integer.parseInt(CONEXAO_EMAIL_LIMITE);
          } catch (NumberFormatException e) {
            e.printStackTrace();
            limiteEmails = 10;
          }

          ArrayList<ClienteEmailCentralServicoMessagesDTO> emailMessages =
              new ArrayList<ClienteEmailCentralServicoMessagesDTO>();

          for (Message message : messages) {
            if (emailMessages.size() < limiteEmails) {
              MimeMessage m = (MimeMessage) inbox.getMessage(message.getMessageNumber());
              EmailSolicitacaoServicoDTO colEmailDto =
                  emailSolicitacaoServicoService.getEmailByIdMessage(m.getMessageID());

              if (colEmailDto == null) {
                ClienteEmailCentralServicoMessagesDTO clienteEmailMessagesDto =
                    new ClienteEmailCentralServicoMessagesDTO();

                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)); //Atrapalha a
                // performance
                clienteEmailMessagesDto.setSeen(true);

                emailMessages.add(clienteEmailMessagesDto);
              }
            } else {
              break;
            }
          }

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

    return clienteEmailCentralServicoDto;
  }