/**
   * 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;
  }
Exemple #2
0
 public static Set<EmailRecipient> getRecipients(Message.RecipientType type, Message message)
     throws MessagingException {
   HashSet<EmailRecipient> out = new HashSet<EmailRecipient>();
   try {
     if (message.getRecipients(type) != null) {
       for (Address recipient : message.getAllRecipients()) {
         String name = "";
         String address = "";
         if (recipient instanceof InternetAddress) {
           if (((InternetAddress) recipient).getPersonal() != null) {
             name = ((InternetAddress) recipient).getPersonal();
           }
           if (((InternetAddress) recipient).getAddress() != null) {
             address = ((InternetAddress) recipient).getAddress();
           }
           RecipientType newType = RecipientType.TO;
           if (type.equals(Message.RecipientType.CC)) {
             newType = RecipientType.CC;
           } else if (type.equals(Message.RecipientType.BCC)) {
             newType = RecipientType.BCC;
           }
           out.add(new EmailRecipient(address, name, newType));
         }
       }
     }
   } catch (AddressException ex) {
     // Do nothing - illegal formatting in recipient field
   }
   return out;
 }
  /*
   * 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());
    }
  }
Exemple #4
0
 public static String getToFormated(Message msg) throws MessagingException {
   StringBuffer sb = new StringBuffer();
   Address[] aa = msg.getRecipients(Message.RecipientType.TO);
   for (int i = 0; i < aa.length; i++) {
     sb.append(aa[i].toString());
     if (i < aa.length - 1) sb.append(", ");
   }
   return sb.toString();
 }
  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");
  }
  public static void fillAddresses(Message mail, RecipientType addrType, List<String> addrList) {
    try {
      Address[] receipients = mail.getRecipients(addrType);

      if (receipients == null) return;

      for (Address address : receipients) {
        addrList.add(address.toString());
      }
    } catch (MessagingException e) {
      throw new RuntimeException(e);
    }
  }
Exemple #7
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());
    }
  }
Exemple #8
0
 public static Set<String> getRecipientsFormated(
     Message msg, javax.mail.Message.RecipientType type) {
   Address[] aa;
   try {
     aa = msg.getRecipients(type);
   } catch (MessagingException ex) {
     throw new RuntimeException(ex);
   }
   Set<String> result = new HashSet<String>();
   if (aa != null) {
     for (Address a : aa) {
       result.add(Str.decodeQuotedPrintable(a.toString()));
     }
   }
   return result;
 }
  @Override
  public void sendMail(boolean isByDepartment, String logsRow, Message message) {
    synchronized (this) {
      // Initialize the Logs Status Attributes
      String status = "Failed Sending TimeSheet";
      String recipient = null;

      try {

        recipient = message.getRecipients(Message.RecipientType.TO)[0].toString();

        logger.info("NOW SENDING MESSAGE TO: " + recipient);

        Transport.send(message);

        status = "Successed Sending TimeSheet";

        logger.info(status + " TO: " + recipient);

      } catch (MessagingException e1) {

        logger.info("Error On Transporting Message: " + e1.toString());
        status = "Failed Sending TimeSheet";
        logger.info(status + " TO: " + recipient);
      }

      if (isByDepartment) {

        try {

          statusQuery.setString(1, logsRow);

          statusQuery.setString(2, recipient);

          statusQuery.setString(3, status);

          statusQuery.addBatch();

        } catch (SQLException e) {

          System.out.println("Error on Preparing the parameters of Log Query: " + e.toString());
        }
      }
    }
  }
 /** Returns the cc field. */
 public String getCc() throws MessagingException {
   return formatAddresses(message.getRecipients(Message.RecipientType.CC));
 }
 /** Method for checking if the message has a to field. */
 public boolean hasTo() throws MessagingException {
   return (message.getRecipients(Message.RecipientType.TO) != null);
 }
Exemple #12
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);
    }
  }
Exemple #13
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;
  }
Exemple #14
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);
    }
  }