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;
 }
Exemplo n.º 2
0
  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;
 }
Exemplo n.º 4
0
  public void sendUdpOneWay(Message message, EndPoint to) {
    EndPoint from = message.getFrom();
    if (message.getFrom().equals(to)) {
      MessagingService.receive(message);
      return;
    }

    UdpConnection connection = null;
    try {
      connection = new UdpConnection();
      connection.init();
      connection.write(message, to);
    } catch (IOException e) {
      logger_.warn(LogUtil.throwableToString(e));
    } finally {
      if (connection != null) connection.close();
    }
  }
Exemplo n.º 5
0
  /*
      Use this version for fire and forget style messaging.
  */
  public void sendOneWay(Message message, EndPoint to) {
    // do local deliveries
    if (message.getFrom().equals(to)) {
      MessagingService.receive(message);
      return;
    }

    Runnable tcpWriteEvent = new MessageSerializationTask(message, to);
    messageSerializerExecutor_.execute(tcpWriteEvent);
  }
  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");
  }
Exemplo n.º 7
0
  private void sendMessageTo(ArrayList<String> addresses, Message message)
      throws MessagingException {
    boolean possibleSend = false;

    close();
    open();

    message.setEncoding(m8bitEncodingAllowed ? "8bit" : null);
    // If the message has attachments and our server has told us about a limit on
    // the size of messages, count the message's size before sending it
    if (mLargestAcceptableMessage > 0 && ((LocalMessage) message).hasAttachments()) {
      if (message.calculateSize() > mLargestAcceptableMessage) {
        MessagingException me = new MessagingException("Message too large for server");
        me.setPermanentFailure(possibleSend);
        throw me;
      }
    }

    Address[] from = message.getFrom();
    try {
      // TODO: Add BODY=8BITMIME parameter if appropriate?
      executeSimpleCommand("MAIL FROM:" + "<" + from[0].getAddress() + ">");
      for (String address : addresses) {
        executeSimpleCommand("RCPT TO:" + "<" + address + ">");
      }
      executeSimpleCommand("DATA");

      EOLConvertingOutputStream msgOut =
          new EOLConvertingOutputStream(
              new SmtpDataStuffing(
                  new LineWrapOutputStream(new BufferedOutputStream(mOut, 1024), 1000)));

      message.writeTo(msgOut);

      // We use BufferedOutputStream. So make sure to call flush() !
      msgOut.flush();

      possibleSend = true; // After the "\r\n." is attempted, we may have sent the message
      executeSimpleCommand("\r\n.");
    } catch (Exception e) {
      MessagingException me = new MessagingException("Unable to send message", e);

      // "5xx text" -responses are permanent failures
      String msg = e.getMessage();
      if (msg != null && msg.startsWith("5")) {
        Log.w(K9.LOG_TAG, "handling 5xx SMTP error code as a permanent failure");
        possibleSend = false;
      }

      me.setPermanentFailure(possibleSend);
      throw me;
    } finally {
      close();
    }
  }
Exemplo n.º 8
0
 /**
  * Puts a message in the database Note: the timestamp will be stored as the current time at which
  * this method is called.
  */
 public void storeMessage(Message message) {
   con.updateDB(
       "INSERT INTO "
           + MESSAGES
           + " VALUES ( \""
           + message.getFrom()
           + "\", \""
           + message.getTo()
           + "\", \""
           + message.getBody()
           + "\", "
           + null
           + ", "
           + message.getType()
           + ")");
 }
Exemplo n.º 9
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>";
    }
  }
Exemplo n.º 10
0
 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
   View v = convertView;
   if (v == null) {
     LayoutInflater vi =
         (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
     v = vi.inflate(R.layout.row, null);
   }
   Message m = items.get(position);
   // if (m != null) {
   m.createColorFromString(m.from);
   TextView tt = (TextView) v.findViewById(R.id.username);
   TextView bt = (TextView) v.findViewById(R.id.message);
   if (isMonospaced) {
     tt.setTypeface(Typeface.MONOSPACE);
     bt.setTypeface(Typeface.MONOSPACE);
   }
   tt.setText(m.getFrom());
   tt.setTextColor(m.color);
   bt.setText(m.getMessage());
   // }
   return v;
 }
Exemplo n.º 11
0
 /** Returns the from field. */
 public String getFrom() throws MessagingException {
   return formatAddresses(message.getFrom());
 }
Exemplo n.º 12
0
 /** Method for checking if the message has a from field. */
 public boolean hasFrom() throws MessagingException {
   return (message.getFrom() != null);
 }
Exemplo n.º 13
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);
    }
  }