public MessagesWrapper print() throws MessagingException {
   logger.info("Found message(s) : " + messages.size());
   for (Message message : messages) {
     logger.info(">>>>>>");
     logger.info("Date    : " + message.getSentDate());
     logger.info("From    : " + (message.getFrom().length > 0 ? message.getFrom()[0] : null));
     logger.info("Subject : " + message.getSubject());
     logger.info("<<<<<<");
   }
   return this;
 }
 /**
  * Adds the senders' from addresses to the end of the issue's details (if they could be
  * extracted), if the e-mail has been received from an unknown e-mail address and the mapping to
  * an "anonymous" user has been enabled.
  *
  * @param reporter the established reporter of the issue (after one has been established)
  * @param message the message that is used to create issue
  * @param description the issues exracted description
  * @return the modified description if the e-mail is from anonymous user, unmodified description
  *     otherwise
  * @throws MessagingException if cannot find out who is the message from
  */
 private String recordFromAddressForAnon(User reporter, Message message, String description)
     throws MessagingException {
   // If the message has been created for an anonymous user add the senders e-mail address to the
   // description.
   if (reporteruserName != null && reporteruserName.equals(reporter.getName())) {
     description += "\n[Created via e-mail ";
     if (message.getFrom() != null && message.getFrom().length > 0) {
       description += "received from: " + message.getFrom()[0] + "]";
     } else {
       description += "but could not establish sender's address.]";
     }
   }
   return description;
 }
  /*
   * This method would print FROM,TO and SUBJECT of the message
   */
  public static void writeEnvelope(Message m, MailInfo mail) throws Exception {
    log.info("This is the message envelope");
    log.info("---------------------------");
    Address[] a;

    // FROM
    if ((a = m.getFrom()) != null) {
      for (int j = 0; j < a.length; j++) {
        log.info("FROM: " + a[j].toString());
        InternetAddress adress = (InternetAddress) a[j];
        mail.setFrom(adress.getAddress());
      }
    }

    // TO
    if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
      for (int j = 0; j < a.length; j++) {
        log.info("TO: " + a[j].toString());
        mail.setTo(a[j].toString());
      }
    }

    // SUBJECT
    if (m.getSubject() != null) {
      log.info("SUBJECT: " + m.getSubject());
      mail.setSubject(m.getSubject());
    }
  }
  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();
      }
    }
  }
 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;
 }
  /**
   * metoda preuzmiPoruke preuzima poruke iz odabrane mape i puni listu poruka
   *
   * @throws MessagingException
   * @throws IOException
   */
  private void preuzmiPoruke() throws MessagingException, IOException {
    Message[] messages;

    // Open the INBOX folder
    folder = store.getFolder(this.odabranaMapa);
    folder.open(Folder.READ_ONLY);

    messages = folder.getMessages();

    this.poruke = new ArrayList<Poruka>();

    for (int i = 0; i < messages.length; ++i) {
      Message m = messages[i];
      Poruka p =
          new Poruka(
              m.getHeader("Message-ID")[0],
              m.getSentDate(),
              m.getFrom()[0].toString(),
              m.getSubject(),
              m.getContentType(),
              m.getSize(),
              0,
              m.getFlags(),
              null,
              true,
              true,
              m.getContent().toString());
      // TODO potraziti broj privitaka, sad je hardkodirano da ih je 0

      this.poruke.add(p);
    }
  }
 /**
  * Helper method for testing which stores a copy of the message locally as the POP3
  *
  * <p>message will be deleted from the server
  *
  * @param msg the message to store
  * @throws IOException If a failure happens writing the message
  * @throws MessagingException If a failure happens reading the message
  */
 protected void storeMessage(Message msg) throws IOException, MessagingException {
   if (backupEnabled) {
     String filename = msg.getFileName();
     if (filename == null) {
       Address[] from = msg.getFrom();
       if (from != null && from.length > 0) {
         filename =
             from[0] instanceof InternetAddress
                 ? ((InternetAddress) from[0]).getAddress()
                 : from[0].toString();
       } else {
         filename = "(no from address)";
       }
       filename += "[" + UUID.getUUID() + "]";
     }
     filename = FileUtils.prepareWinFilename(filename);
     filename = backupFolder + filename + ".msg";
     if (logger.isDebugEnabled()) {
       logger.debug("Writing message to: " + filename);
     }
     File f = FileUtils.createFile(filename);
     FileOutputStream fos = new FileOutputStream(f);
     msg.writeTo(fos);
   }
 }
Esempio n. 8
0
  public static void sendSmtpMessage(Session session, Message message, Address[] recipients)
      throws MessagingException {

    // message = cloneMimeMessage(message);
    message.setSentDate(new Date());
    setHeaderFieldValue(message, HEADER_X_MAILER, X_MAILER);
    message.saveChanges();

    LOG.info(
        "Sending message '"
            + message.getSubject()
            + "' from '"
            + Str.format(message.getFrom())
            + "' to '"
            + Str.format(recipients)
            + "'.");

    Transport trans = session.getTransport("smtp");
    Properties properties = session.getProperties();
    trans.connect(
        properties.getProperty("mail.smtp.host"),
        properties.getProperty("mail.smtp.auth.user"),
        properties.getProperty("mail.smtp.auth.password"));
    trans.sendMessage(message, recipients);
    trans.close();
  }
  /**
   * Fetches all e-mail headers from the server, with appropriate fields already set.
   *
   * @param handler
   * @return ArrayList of MessageHeaders
   * @throws ConnectionException
   */
  public ArrayList fetchAllHeaders() throws SystemException, ConnectionException {
    ArrayList headers = null;
    Folder fold = null;
    try {
      fold = getFolder();
      closeFolder(fold);
      fold = getFolder();

      headers = new ArrayList();
      EmailHeader header = null;

      Message[] msgs = fold.getMessages();
      FetchProfile fp = new FetchProfile();
      fp.add(FetchProfile.Item.ENVELOPE);
      fp.add(FetchProfile.Item.FLAGS);
      fp.add(FetchProfile.Item.CONTENT_INFO);
      fp.add("Size");
      fp.add("Date");
      fold.fetch(msgs, fp);

      Message msg = null;
      for (int i = 0; i < msgs.length; i++) {
        try {
          header = new EmailHeader();
          msg = msgs[i];

          header.setMultipart((msg.isMimeType("multipart/*")) ? true : false);
          header.setMessageId(i + 1);
          header.setFrom(msg.getFrom());
          header.setTo(msg.getRecipients(Message.RecipientType.TO));
          header.setCc(msg.getRecipients(Message.RecipientType.CC));
          header.setBcc(msg.getRecipients(Message.RecipientType.BCC));
          header.setDate(msg.getSentDate());
          header.setReplyTo(msg.getReplyTo());
          header.setSize(msg.getSize());
          header.setSubject(msg.getSubject());

          // now set the human readables.
          header.setDateShown(Formatter.formatDate(header.getDate(), "dd.MM.yyyy HH:mm"));
          header.setFromShown(Utility.addressArrToString(header.getFrom()));
          header.setToShown(Utility.addressArrToString(header.getTo()));
          header.setCcShown(Utility.addressArrToString(header.getCc()));
          header.setSizeShown(Utility.sizeToHumanReadable(header.getSize()));

          // it is time to add it to the arraylist
          headers.add(header);
        } catch (MessagingException e1) {
          System.out.println(
              "Could not parse headers of e-mail. Message might be defuncted or illegal formatted.");
        }
      }
    } catch (Exception e) {
      System.out.println("Could not fetch message headers. Is mbox connection still alive???");
      throw new ConnectionException(e);
    }
    return headers;
  }
  public static void dumpEnvelope(Message m) throws Exception {
    pr("This is the message envelope");
    pr("---------------------------");
    Address[] a;
    // FROM
    if ((a = m.getFrom()) != null) {
      for (int j = 0; j < a.length; j++) pr("FROM: " + a[j].toString());
    }

    // TO
    if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
      for (int j = 0; j < a.length; j++) pr("TO: " + a[j].toString());
    }

    // SUBJECT
    pr("SUBJECT: " + m.getSubject());

    // DATE
    Date d = m.getSentDate();
    pr("SendDate: " + (d != null ? d.toString() : "UNKNOWN"));

    // FLAGS
    Flags flags = m.getFlags();
    StringBuffer sb = new StringBuffer();
    Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags

    boolean first = true;
    for (int i = 0; i < sf.length; i++) {
      String s;
      Flags.Flag f = sf[i];
      if (f == Flags.Flag.ANSWERED) s = "\\Answered";
      else if (f == Flags.Flag.DELETED) s = "\\Deleted";
      else if (f == Flags.Flag.DRAFT) s = "\\Draft";
      else if (f == Flags.Flag.FLAGGED) s = "\\Flagged";
      else if (f == Flags.Flag.RECENT) s = "\\Recent";
      else if (f == Flags.Flag.SEEN) s = "\\Seen";
      else continue; // skip it
      if (first) first = false;
      else sb.append(' ');
      sb.append(s);
    }

    String[] uf = flags.getUserFlags(); // get the user flag strings
    for (int i = 0; i < uf.length; i++) {
      if (first) first = false;
      else sb.append(' ');
      sb.append(uf[i]);
    }
    pr("FLAGS: " + sb.toString());

    // X-MAILER
    String[] hdrs = m.getHeader("X-Mailer");
    if (hdrs != null) pr("X-Mailer: " + hdrs[0]);
    else pr("X-Mailer NOT available");
  }
  private void receiveMail() {
    String username = USERNAME;
    String password = PASSWORD;

    try {
      ServerConfigProvider provider = ServerConfigFactory.fromEmailAdress(username);
      MailReceiver mailReceiver = new MailReceiver(provider, new User(username, password));

      for (Folder folders : mailReceiver.getFolders()) {
        try {
          System.out.println(folders.getFullName() + " " + folders.getMessageCount());
        } catch (Exception e) {
          System.err.println(e.getMessage());
        }
      }

      Folder folder = mailReceiver.getFolderByName("Inbox");
      folder.open(Folder.READ_ONLY);
      for (Message message : folder.getMessages()) {
        List<File> attachments =
            MessageHelper.getAttachments(Environment.getExternalStorageDirectory(), message);
        if (!attachments.isEmpty()) {
          for (File attachment : attachments) {
            System.out.println(
                String.format(
                    "from %s subject %s attachmentname %s",
                    message.getFrom()[0], message.getSubject(), attachment.getName()));
          }
        } else {
          System.out.println(
              String.format(
                  "from %s subject %s no attachement", message.getFrom()[0], message.getSubject()));
        }
      }

      mailReceiver.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Esempio n. 12
0
  /**
   * The address comparator.
   *
   * @param msg The address comparison is applied to this Message
   * @return true if the comparison succeeds, otherwise false
   */
  public boolean match(Message msg) {
    Address[] from;

    try {
      from = msg.getFrom();
    } catch (Exception e) {
      return false;
    }

    if (from == null) return false;

    for (int i = 0; i < from.length; i++) if (super.match(from[i])) return true;
    return false;
  }
Esempio n. 13
0
  public String toString() {
    try {
      Address from = m.getFrom()[0];

      String fromAddress;
      if (from instanceof InternetAddress) fromAddress = ((InternetAddress) from).getAddress();
      else fromAddress = from.toString();

      StringBuffer sb = new StringBuffer();
      fromFmt.format(fromAddress, sb, null);
      sb.append("  ");
      subjFmt.format(m.getSubject(), sb, null);
      return sb.toString();
    } catch (Exception e) {
      return e.toString();
    }
  }
Esempio n. 14
0
 public static String getFromFormated(Message msg) {
   StringBuffer sb = new StringBuffer();
   Address[] aa;
   try {
     aa = msg.getFrom();
   } catch (MessagingException ex) {
     throw new RuntimeException(ex);
   }
   if (aa == null) {
     sb.append("<Kein Absender>");
   } else {
     for (int i = 0; i < aa.length; i++) {
       sb.append(Str.decodeQuotedPrintable(aa[i].toString()));
       if (i < aa.length - 1) sb.append(", ");
     }
   }
   return sb.toString();
 }
Esempio n. 15
0
  private String getFrom() {

    String from = "";

    try {
      Address[] fromArray = message.getFrom();
      for (int i = 0; i < fromArray.length; i++) {
        from = fromArray[i].toString();
      }

      from = removeBrackets(from);

    } catch (MessagingException e) {
      e.printStackTrace();
    }

    return from;
  }
Esempio n. 16
0
 // 读取邮件内容
 @SuppressWarnings({"rawtypes", "unchecked"})
 public Map readMail(String id) throws Exception {
   Map map = new HashMap();
   // 找到目标邮件
   Message readmsg = findMail(msg, id);
   // 读取邮件标题
   map.put("subject", readmsg.getSubject());
   // 读取发件人
   map.put("sender", MimeUtility.decodeText(readmsg.getFrom()[0].toString()));
   map.put("attach", "");
   // 取得邮件内容
   if (readmsg.isMimeType("text/*")) {
     map.put("content", readmsg.getContent().toString());
   } else {
     System.out.println("this is not a text mail");
     Multipart mp = (Multipart) readmsg.getContent();
     if (mp == null) {
       System.out.println("the content is null");
     } else System.out.println("--------------------------multipart:" + mp.toString());
     BodyPart part = null;
     String disp = null;
     StringBuffer result = new StringBuffer();
     // 遍历每个Miltipart对象
     for (int j = 0; j < mp.getCount(); j++) {
       part = mp.getBodyPart(j);
       disp = part.getDisposition();
       // 如果有附件
       if (disp != null && (disp.equals(Part.ATTACHMENT) || disp.equals(Part.INLINE))) {
         // 取得附件文件名
         String filename = MimeUtility.decodeText(part.getFileName()); // 解决中文附件名的问题
         map.put("attach", filename);
         // 下载附件
         InputStream in = part.getInputStream(); // 附件输入流
         if (attachFile.isDownload(filename)) attachFile.choicePath(filename, in); // // 下载附件
       } else {
         // 显示复杂邮件正文内容
         result.append(getPart(part, j, 1));
       }
     }
     map.put("content", result.toString());
   }
   return map;
 }
Esempio n. 17
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>";
    }
  }
Esempio n. 18
0
  protected void sendMailMessage(Message message) throws MessagingException {
    // sent date
    message.setSentDate(Calendar.getInstance().getTime());

    /*
     * Double check that the transport is still connected as some SMTP servers may
     * disconnect idle connections.
     */
    if (!transport.isConnected()) {
      EndpointURI uri = endpoint.getEndpointURI();
      if (logger.isInfoEnabled()) {
        logger.info("Connection closed by remote server. Reconnecting.");
      }
      transport.connect(uri.getHost(), uri.getPort(), uri.getUser(), uri.getPassword());
    }

    transport.sendMessage(message, message.getAllRecipients());

    if (logger.isDebugEnabled()) {
      StringBuffer msg = new StringBuffer();
      msg.append("Email message sent with subject'")
          .append(message.getSubject())
          .append("' sent- ");
      msg.append(", From: ").append(MailUtils.mailAddressesToString(message.getFrom())).append(" ");
      msg.append(", To: ")
          .append(MailUtils.mailAddressesToString(message.getRecipients(Message.RecipientType.TO)))
          .append(" ");
      msg.append(", Cc: ")
          .append(MailUtils.mailAddressesToString(message.getRecipients(Message.RecipientType.CC)))
          .append(" ");
      msg.append(", Bcc: ")
          .append(MailUtils.mailAddressesToString(message.getRecipients(Message.RecipientType.BCC)))
          .append(" ");
      msg.append(", ReplyTo: ").append(MailUtils.mailAddressesToString(message.getReplyTo()));

      logger.debug(msg.toString());
    }
  }
Esempio n. 19
0
 private void mailReceiver(Message msg) throws Exception {
   // 发件人信息
   Address[] froms = msg.getFrom();
   if (froms != null) {
     // System.out.println("发件人信息:" + froms[0]);
     InternetAddress addr = (InternetAddress) froms[0];
     System.out.println("发件人地址:" + addr.getAddress());
     System.out.println("发件人显示名:" + addr.getPersonal());
   }
   System.out.println("邮件主题:" + msg.getSubject());
   // getContent() 是获取包裹内容, Part相当于外包装
   Object o = msg.getContent();
   if (o instanceof Multipart) {
     Multipart multipart = (Multipart) o;
     reMultipart(multipart);
   } else if (o instanceof Part) {
     Part part = (Part) o;
     rePart(part);
   } else {
     System.out.println("类型" + msg.getContentType());
     System.out.println("内容" + msg.getContent());
   }
 }
Esempio n. 20
0
  private static void replayError(Message msg, String subject, String body, String string)
      throws SQLException, MessagingException, IOException {
    log("Sending error to " + string);
    log("Message:\n" + msg.toString());

    String connStr = "jdbc:mysql://" + properties.getProperty("db");
    // System.out.println("Database: " + connStr);
    Connection connection =
        DriverManager.getConnection(
            connStr, properties.getProperty("user"), properties.getProperty("pass"));

    String usermail = null;
    Address[] from = msg.getFrom();
    for (int i = 0; i < from.length; i++) {
      if (from[i] instanceof InternetAddress) {
        usermail = ((InternetAddress) from[i]).getAddress();
      }
    }
    if (usermail == null) {
      return;
    }

    // verification email
    String email = "From: " + properties.getProperty("message_from") + "\n";
    email += "To: " + usermail + "\n";
    email += "Subject: Submission error\n";
    email += "Your submission encountered a problem:\n" + string + "\n\n";
    // email += "Post subject: " + subject + "\n\n";
    // email += "Post content: \n" + body + "\n";

    // System.out.println("Message is:");
    // System.out.println(email);

    send(email, usermail);

    System.exit(0);
  }
Esempio n. 21
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 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;
  }
  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 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;
  }
Esempio n. 25
0
  public static void dumpPart(Part p) throws Exception {
    if (p instanceof Message) {
      Message m = (Message) p;
      Address[] a;
      // FROM
      if ((a = m.getFrom()) != null) {
        for (int j = 0; j < a.length; j++) System.out.println("FROM: " + a[j].toString());
      }

      // TO
      if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
        for (int j = 0; j < a.length; j++) System.out.println("TO: " + a[j].toString());
      }

      // SUBJECT
      System.out.println("SUBJECT: " + m.getSubject());

      // DATE
      Date d = m.getSentDate();
      System.out.println("SendDate: " + (d != null ? d.toLocaleString() : "UNKNOWN"));

      // FLAGS:
      Flags flags = m.getFlags();
      StringBuffer sb = new StringBuffer();
      Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags

      boolean first = true;
      for (int i = 0; i < sf.length; i++) {
        String s;
        Flags.Flag f = sf[i];
        if (f == Flags.Flag.ANSWERED) s = "\\Answered";
        else if (f == Flags.Flag.DELETED) s = "\\Deleted";
        else if (f == Flags.Flag.DRAFT) s = "\\Draft";
        else if (f == Flags.Flag.FLAGGED) s = "\\Flagged";
        else if (f == Flags.Flag.RECENT) s = "\\Recent";
        else if (f == Flags.Flag.SEEN) s = "\\Seen";
        else continue; // skip it
        if (first) first = false;
        else sb.append(' ');
        sb.append(s);
      }

      String[] uf = flags.getUserFlags(); // get the user flag strings
      for (int i = 0; i < uf.length; i++) {
        if (first) first = false;
        else sb.append(' ');
        sb.append(uf[i]);
      }
      System.out.println("FLAGS = " + sb.toString());
    }

    System.out.println("CONTENT-TYPE: " + p.getContentType());

    /* Dump input stream
    InputStream is = ((MimeMessage)m).getInputStream();
    int c;
    while ((c = is.read()) != -1)
        System.out.write(c);
    */

    Object o = p.getContent();
    if (o instanceof String) {
      System.out.println("This is a String");
      System.out.println((String) o);
    } else if (o instanceof Multipart) {
      System.out.println("This is a Multipart");
      Multipart mp = (Multipart) o;
      int count = mp.getCount();
      for (int i = 0; i < count; i++) dumpPart(mp.getBodyPart(i));
    } else if (o instanceof InputStream) {
      System.out.println("This is just an input stream");
      InputStream is = (InputStream) o;
      int c;
      while ((c = is.read()) != -1) System.out.write(c);
    }
  }
Esempio n. 26
0
 /** Returns the from field. */
 public String getFrom() throws MessagingException {
   return formatAddresses(message.getFrom());
 }
Esempio n. 27
0
 /** Method for checking if the message has a from field. */
 public boolean hasFrom() throws MessagingException {
   return (message.getFrom() != null);
 }
Esempio n. 28
0
  /**
   * Fetches all e-mail headers from the server, with appropriate fields already set.
   *
   * @param handler
   * @return ArrayList of MessageHeaders
   * @throws ConnectionException
   */
  public ArrayList fetchAllHeaders() throws SystemException, ConnectionException {
    ArrayList headers = new ArrayList();
    Folder fold = null;
    try {
      fold = getFolder();
      EmailHeader header = null;

      Message[] msgs = fold.getMessages();
      FetchProfile fp = new FetchProfile();
      fp.add(FetchProfile.Item.ENVELOPE);
      fp.add(FetchProfile.Item.FLAGS);
      fp.add(FetchProfile.Item.CONTENT_INFO);
      fp.add("Size");
      fp.add("Date");
      fp.add("Disposition-Notification-To");
      fp.add("X-Priority");
      fp.add("X-MSMail-Priority");
      fp.add("Sensitivity");
      fold.fetch(msgs, fp);

      Message msg = null;
      for (int i = 0; i < msgs.length; i++) {
        try {
          header = new EmailHeader();
          msg = msgs[i];

          header.setMultipart((msg.isMimeType("multipart/*")) ? true : false);
          header.setMessageId(i + 1);
          header.setFrom(msg.getFrom());
          header.setTo(msg.getRecipients(Message.RecipientType.TO));
          header.setCc(msg.getRecipients(Message.RecipientType.CC));
          header.setBcc(msg.getRecipients(Message.RecipientType.BCC));
          header.setDate(msg.getSentDate());
          header.setReplyTo(msg.getReplyTo());
          header.setSize(msg.getSize());
          header.setSubject(org.claros.commons.utility.Utility.updateTRChars(msg.getSubject()));

          // now set the human readables.
          header.setDateShown(Formatter.formatDate(header.getDate(), "dd.MM.yyyy HH:mm"));
          header.setFromShown(
              org.claros.commons.utility.Utility.updateTRChars(
                  Utility.addressArrToStringShort(header.getFrom())));
          header.setToShown(Utility.addressArrToStringShort(header.getTo()));
          header.setCcShown(Utility.addressArrToStringShort(header.getCc()));
          header.setSizeShown(Utility.sizeToHumanReadable(header.getSize()));

          org.claros.commons.mail.parser.MessageParser.setHeaders(msg, header);

          boolean deleted = false;
          if (profile.getProtocol().equals(Constants.IMAP)) {
            Flags.Flag flags[] = msg.getFlags().getSystemFlags();
            if (flags != null) {
              Flags.Flag flag = null;
              for (int m = 0; m < flags.length; m++) {
                flag = flags[m];
                if (flag.equals(Flags.Flag.SEEN)) {
                  header.setUnread(new Boolean(false));
                }

                if (flag.equals(Flags.Flag.DELETED)) {
                  deleted = true;
                }
              }
            }
          }
          if (header.getUnread() == null) {
            header.setUnread(new Boolean(true));
          }

          // it is time to add it to the arraylist
          if (!deleted) {
            headers.add(header);
          }
        } catch (MessagingException e1) {
          log.error(
              "Could not parse headers of e-mail. Message might be defuncted or illegal formatted.",
              e1);
        }
      }
    } catch (MessagingException e) {
      log.error("Could not fetch message headers. Is mbox connection still alive???", e);
      //			throw new ConnectionException(e);
    } catch (Exception e) {
      log.error("Could not fetch message headers. Is mbox connection still alive???", e);
      //			throw new ConnectionException(e);
    }
    return headers;
  }
Esempio n. 29
0
 /**
  * Returns the author of this message. If the message does not have a <code>from</code> field, an
  * {@link IllegalArgumentException} is thrown.
  *
  * @param message the e-mail message
  * @return the sender
  * @throws MessagingException if reading the message's author fails
  * @throws IllegalArgumentException if no author can be found
  */
 private String getAuthor(Message message) throws MessagingException, IllegalArgumentException {
   Address[] address = message.getFrom();
   if (address == null || address.length == 0)
     throw new MessagingException("Message has no author");
   return address[0].toString();
 }
Esempio n. 30
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);
    }
  }