示例#1
0
 public Date getMessageDate(Message message) throws MessagingException {
   Date messageDate = message.getReceivedDate();
   if (message.getReceivedDate() == null) {
     if (message.getSentDate() != null) {
       messageDate = message.getSentDate();
     }
   }
   return messageDate;
 }
示例#2
0
  public int handleFirstTime(
      Account account,
      FolderHelper folderHelper,
      int folderDepth,
      String messageStoreBucket,
      Set<String> storedMessageIds,
      String context,
      StopWatch watch)
      throws Exception {
    int newMessages = 0;
    Date lastMessageReceivedDate = null;
    log.info(String.format("handling first mailcheck for %s", context));

    Folder folder;
    while ((folder = folderHelper.next()) != null) {
      String folderContext = context + " ,folderName=" + folder.getFullName();
      IMAPFolder imapFolder = (IMAPFolder) folder;

      Collection<Integer> messages = getFirstTimeMessages(imapFolder, folderContext);

      if (messages.size() > 0) {
        storedMessageIds = new HashSet<String>();

        for (Integer messageNumber : messages) {
          Message message = imapFolder.getMessage(messageNumber);

          if (lastMessageReceivedDate == null
              || lastMessageReceivedDate.before(message.getReceivedDate())) {
            lastMessageReceivedDate = message.getReceivedDate();
          }

          String messageId = getId(account, imapFolder, message);

          if (processMessage(
              account,
              message,
              messageNumber,
              messageId,
              imapFolder,
              storedMessageIds,
              messageStoreBucket,
              folderContext,
              watch,
              folderHelper)) {
            newMessages++;
          }
        }
      }
    }
    updateAccount(account, null, 0, folderDepth, lastMessageReceivedDate);
    return newMessages;
  }
  public static void main(String[] args) throws MessagingException, IOException {
    IMAPFolder folder = null;
    Store store = null;
    String subject = null;
    Flag flag = null;
    try {
      Properties props = System.getProperties();
      props.setProperty("mail.store.protocol", "imaps");
      props.setProperty("mail.imap.host", "imap.googlemail.com");
      SimpleAuthenticator authenticator =
          new SimpleAuthenticator("*****@*****.**", "hhy8611hhyy");
      Session session = Session.getDefaultInstance(props, null);
      // Session session = Session.getDefaultInstance(props, authenticator);

      store = session.getStore("imaps");
      //          store.connect("imap.googlemail.com","*****@*****.**", "hhy8611hhyy");
      // store.connect("imap.googlemail.com","*****@*****.**", "hhy8611hhyy");

      store.connect("*****@*****.**", "hhy8611hhy");
      // folder = (IMAPFolder) store.getFolder("[Gmail]/Spam"); // This doesn't work for other email
      // account
      folder = (IMAPFolder) store.getFolder("inbox"); // This works for both email account

      if (!folder.isOpen()) folder.open(Folder.READ_WRITE);
      Message[] messages = messages = folder.getMessages(150, 150); // folder.getMessages();
      System.out.println("No of get Messages : " + messages.length);
      System.out.println("No of Messages : " + folder.getMessageCount());
      System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount());
      System.out.println("No of New Messages : " + folder.getNewMessageCount());
      System.out.println(messages.length);
      for (int i = 0; i < messages.length; i++) {

        System.out.println(
            "*****************************************************************************");
        System.out.println("MESSAGE " + (i + 1) + ":");
        Message msg = messages[i];
        // System.out.println(msg.getMessageNumber());
        // Object String;
        // System.out.println(folder.getUID(msg)

        subject = msg.getSubject();

        System.out.println("Subject: " + subject);
        System.out.println("From: " + msg.getFrom()[0]);
        System.out.println("To: " + msg.getAllRecipients()[0]);
        System.out.println("Date: " + msg.getReceivedDate());
        System.out.println("Size: " + msg.getSize());
        System.out.println(msg.getFlags());
        System.out.println("Body: \n" + msg.getContent());
        System.out.println(msg.getContentType());
      }
    } finally {
      if (folder != null && folder.isOpen()) {
        folder.close(true);
      }
      if (store != null) {
        store.close();
      }
    }
  }
 /** Returns the date the message was sent (or received if the sent date is null. */
 public String getDate() throws MessagingException {
   Date date;
   SimpleDateFormat df = new SimpleDateFormat("EE M/d/yy");
   if ((date = message.getSentDate()) != null) return (df.format(date));
   else if ((date = message.getReceivedDate()) != null) return (df.format(date));
   else return "";
 }
 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;
 }
  @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;
    }

    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;
  }
 /** Creates a new instance of RenderablePlainText */
 public RenderablePlainText(Message message) throws MessagingException, IOException {
   subject = message.getSubject();
   bodytext = (String) message.getContent();
   receivedOn = message.getReceivedDate();
   if (!StringUtils.isNull(bodytext)) {
     if (bodytext.indexOf("Original Message") > -1) {
       subBody = bodytext.substring(0, bodytext.indexOf("Original Message"));
     }
     if (!StringUtils.isNull(bodytext)
         && bodytext.indexOf(", \"[email protected]\" <*****@*****.**> wrote:") > -1) {
       String tempstr =
           bodytext.substring(
               0, bodytext.indexOf(", \"[email protected]\" <*****@*****.**> wrote:"));
       subBody = tempstr.substring(0, tempstr.lastIndexOf("On"));
     }
   }
 }
示例#8
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>";
    }
  }
示例#9
0
  /**
   * Aggregates the e-mail message by reading it and turning it either into a page or a file upload.
   *
   * @param message the e-mail message
   * @param site the site to publish to
   * @throws MessagingException if fetching the message data fails
   * @throws IOException if writing the contents to the output stream fails
   */
  protected Page aggregate(Message message, Site site)
      throws IOException, MessagingException, IllegalArgumentException {

    ResourceURI uri = new PageURIImpl(site, UUID.randomUUID().toString());
    Page page = new PageImpl(uri);
    Language language = site.getDefaultLanguage();

    // Extract title and subject. Without these two, creating a page is not
    // feasible, therefore both messages throw an IllegalArgumentException if
    // the fields are not present.
    String title = getSubject(message);
    String author = getAuthor(message);

    // Collect default settings
    PageTemplate template = site.getDefaultTemplate();
    if (template == null)
      throw new IllegalStateException("Missing default template in site '" + site + "'");
    String stage = template.getStage();
    if (StringUtils.isBlank(stage))
      throw new IllegalStateException(
          "Missing stage definition in template '" + template.getIdentifier() + "'");

    // Standard fields
    page.setTitle(title, language);
    page.setTemplate(template.getIdentifier());
    page.setPublished(new UserImpl(site.getAdministrator()), message.getReceivedDate(), null);

    // TODO: Translate e-mail "from" into site user and throw if no such
    // user can be found
    page.setCreated(site.getAdministrator(), message.getSentDate());

    // Start looking at the message body
    String contentType = message.getContentType();
    if (StringUtils.isBlank(contentType))
      throw new IllegalArgumentException("Message content type is unspecified");

    // Text body
    if (contentType.startsWith("text/plain")) {
      // TODO: Evaluate charset
      String body = null;
      if (message.getContent() instanceof String) body = (String) message.getContent();
      else if (message.getContent() instanceof InputStream)
        body = IOUtils.toString((InputStream) message.getContent());
      else throw new IllegalArgumentException("Message body is of unknown type");
      return handleTextPlain(body, page, language);
    }

    // HTML body
    if (contentType.startsWith("text/html")) {
      // TODO: Evaluate charset
      return handleTextHtml((String) message.getContent(), page, null);
    }

    // Multipart body
    else if ("mime/multipart".equalsIgnoreCase(contentType)) {
      Multipart mp = (Multipart) message.getContent();
      for (int i = 0, n = mp.getCount(); i < n; i++) {
        Part part = mp.getBodyPart(i);
        String disposition = part.getDisposition();
        if (disposition == null) {
          MimeBodyPart mbp = (MimeBodyPart) part;
          if (mbp.isMimeType("text/plain")) {
            return handleTextPlain((String) mbp.getContent(), page, null);
          } else {
            // TODO: Implement special non-attachment cases here of
            // image/gif, text/html, ...
            throw new UnsupportedOperationException(
                "Multipart message bodies of type '"
                    + mbp.getContentType()
                    + "' are not yet supported");
          }
        } else if (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE)) {
          logger.info("Skipping message attachment " + part.getFileName());
          // saveFile(part.getFileName(), part.getInputStream());
        }
      }

      throw new IllegalArgumentException(
          "Multipart message did not contain any recognizable content");
    }

    // ?
    else {
      throw new IllegalArgumentException("Message body is of unknown type '" + contentType + "'");
    }
  }
  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;
  }
 /** Creates a new instance of RenderableMessage */
 public RenderableMessage(Message m) throws MessagingException, IOException {
   subject = m.getSubject();
   attachments = new ArrayList<Attachment>();
   receivedOn = m.getReceivedDate();
   extractPart(m);
 }
 /** Returns the received date field. */
 public String getReceivedDate() throws MessagingException {
   if (hasReceivedDate()) return (message.getReceivedDate().toString());
   else return "";
 }
 /** Method for checking if the message has a received date field. */
 public boolean hasReceivedDate() throws MessagingException {
   return (message.getReceivedDate() != null);
 }
 private Message mockMessage(Date date, String subject) throws MessagingException {
   Message message1 = mock(Message.class);
   when(message1.getReceivedDate()).thenReturn(date);
   when(message1.getSubject()).thenReturn(subject);
   return message1;
 }
  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;
  }
示例#16
0
 private Date getDateToDetermineOrder(Message message) throws MessagingException {
   return message instanceof IMAPMessage ? message.getReceivedDate() : message.getSentDate();
 }
示例#17
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;
  }
  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 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();
    }
  }
示例#20
0
  /**
   * Receive Email from POPServer. Use POP3 protocal by default. Thus, call this method, you need to
   * provide a pop3 mail server address.
   *
   * @param emailAddress The email account in the POPServer.
   * @param password The password of email address.
   */
  public static void receiveEmail(String host, String username, String password) {
    // param check. If param is null, use the default configured value.
    if (host == null) {
      host = POP3Server;
    }
    if (username == null) {
      username = POP3Username;
    }
    if (password == null) {
      password = POP3Password;
    }
    Properties props = System.getProperties();
    // MailAuthenticator authenticator = new MailAuthenticator(username, password);
    try {
      Session session = Session.getDefaultInstance(props, null);
      // Store store = session.getStore("imap");
      Store store = session.getStore("pop3");
      // Connect POPServer
      store.connect(host, username, password);
      Folder inbox = store.getFolder("INBOX");
      if (inbox == null) {
        throw new RuntimeException("No inbox existed.");
      }
      // Open the INBOX with READ_ONLY mode and start to read all emails.
      inbox.open(Folder.READ_ONLY);
      System.out.println("TOTAL EMAIL:" + inbox.getMessageCount());
      Message[] messages = inbox.getMessages();
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      for (int i = 0; i < messages.length; i++) {
        Message msg = messages[i];
        String from = InternetAddress.toString(msg.getFrom());
        String replyTo = InternetAddress.toString(msg.getReplyTo());
        String to = InternetAddress.toString(msg.getRecipients(Message.RecipientType.TO));
        String subject = msg.getSubject();
        Date sent = msg.getSentDate();
        Date ress = msg.getReceivedDate();
        String type = msg.getContentType();
        System.out.println((i + 1) + ".---------------------------------------------");
        System.out.println("From:" + mimeDecodeString(from));
        System.out.println("Reply To:" + mimeDecodeString(replyTo));
        System.out.println("To:" + mimeDecodeString(to));
        System.out.println("Subject:" + mimeDecodeString(subject));
        System.out.println("Content-type:" + type);
        if (sent != null) {
          System.out.println("Sent Date:" + sdf.format(sent));
        }
        if (ress != null) {
          System.out.println("Receive Date:" + sdf.format(ress));
        }
        //                //Get message headers.
        //                @SuppressWarnings("rawtypes")
        //                Enumeration headers = msg.getAllHeaders();
        //                while (headers.hasMoreElements()) {
        //                    Header h = (Header) headers.nextElement();
        //                    String name = h.getName();
        //                    String val = h.getValue();
        //                    System.out.println(name + ": " + val);
        //                }

        //                //get the email content.
        //                Object content = msg.getContent();
        //                System.out.println(content);
        //                //print content
        //                Reader reader = new InputStreamReader(
        //                        messages[i].getInputStream());
        //                int a = 0;
        //                while ((a = reader.read()) != -1) {
        //                    System.out.print((char) a);
        //                }
      }
      // close connection. param false represents do not delete messaegs on server.
      inbox.close(false);
      store.close();
      //        } catch(IOException e) {
      //            LOGGER.error("IOException caught while printing the email content", e);
    } catch (MessagingException e) {
      LOGGER.error("MessagingException caught when use message object", e);
    }
  }