Access message given its UID and Show information about and contents of messages : Email Message « Email « Java

Home
Java
1.2D Graphics GUI
2.3D
3.Advanced Graphics
4.Ant
5.Apache Common
6.Chart
7.Class
8.Collections Data Structure
9.Data Type
10.Database SQL JDBC
11.Design Pattern
12.Development Class
13.EJB3
14.Email
15.Event
16.File Input Output
17.Game
18.Generics
19.GWT
20.Hibernate
21.I18N
22.J2EE
23.J2ME
24.JavaFX
25.JDK 6
26.JDK 7
27.JNDI LDAP
28.JPA
29.JSP
30.JSTL
31.Language Basics
32.Network Protocol
33.PDF RTF
34.Reflection
35.Regular Expressions
36.Scripting
37.Security
38.Servlets
39.Spring
40.Swing Components
41.Swing JFC
42.SWT JFace Eclipse
43.Threads
44.Tiny Application
45.Velocity
46.Web Services SOA
47.XML
Java » Email » Email Message 




Access message given its UID and Show information about and contents of messages
 
 
/*
 * @(#)uidmsgshow.java  1.6 03/04/22
 *
 * Copyright 1997-2003 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 
 * - Redistribution in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 
 * Neither the name of Sun Microsystems, Inc. or the names of contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
 * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND
 * ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES OR LIABILITIES
 * SUFFERED BY LICENSEE AS A RESULT OF  OR RELATING TO USE, MODIFICATION
 * OR DISTRIBUTION OF THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL
 * SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR
 * FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
 * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
 * ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS
 * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 
 * You acknowledge that Software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */

import java.io.InputStream;
import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.FetchProfile;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.UIDFolder;
import javax.mail.URLName;

/*
 * Demo app that exercises the Message interfaces. Access message given its UID.
 * Show information about and contents of messages.
 
 * @author John Mani @author Bill Shannon
 */

public class uidmsgshow {

  static String protocol;

  static String host = null;

  static String user = null;

  static String password = null;

  static String mbox = "INBOX";

  static String url = null;

  static boolean verbose = false;

  public static void main(String argv[]) {
    long uid = -1;
    int optind;

    for (optind = 0; optind < argv.length; optind++) {
      if (argv[optind].equals("-T")) {
        protocol = argv[++optind];
      else if (argv[optind].equals("-H")) {
        host = argv[++optind];
      else if (argv[optind].equals("-U")) {
        user = argv[++optind];
      else if (argv[optind].equals("-P")) {
        password = argv[++optind];
      else if (argv[optind].equals("-v")) {
        verbose = true;
      else if (argv[optind].equals("-f")) {
        mbox = argv[++optind];
      else if (argv[optind].equals("-L")) {
        url = argv[++optind];
      else if (argv[optind].equals("--")) {
        optind++;
        break;
      else if (argv[optind].startsWith("-")) {
        System.out
            .println("Usage: uidmsgshow [-L url] [-T protocol] [-H host] [-U user] [-P password] [-f mailbox] [uid] [-v]");
        System.exit(1);
      else {
        break;
      }
    }

    try {
      if (optind < argv.length)
        uid = Long.parseLong(argv[optind]);

      // Get a Properties object
      Properties props = System.getProperties();

      // Get a Session object
      Session session = Session.getInstance(props, null);
      // session.setDebug(true);

      // Get a Store object
      Store store = null;
      if (url != null) {
        URLName urln = new URLName(url);
        store = session.getStore(urln);
        store.connect();
      else {
        if (protocol != null)
          store = session.getStore(protocol);
        else
          store = session.getStore();

        // Connect
        if (host != null || user != null || password != null)
          store.connect(host, user, password);
        else
          store.connect();
      }

      // Open the Folder

      Folder folder = store.getDefaultFolder();
      if (folder == null) {
        System.out.println("No default folder");
        System.exit(1);
      }

      folder = folder.getFolder(mbox);
      if (!folder.exists()) {
        System.out.println(mbox + "  does not exist");
        System.exit(1);
      }

      if (!(folder instanceof UIDFolder)) {
        System.out.println("This Provider or this folder does not support UIDs");
        System.exit(1);
      }

      UIDFolder ufolder = (UIDFolderfolder;

      folder.open(Folder.READ_WRITE);
      int totalMessages = folder.getMessageCount();

      if (totalMessages == 0) {
        System.out.println("Empty folder");
        folder.close(false);
        store.close();
        System.exit(1);
      }

      if (verbose) {
        int newMessages = folder.getNewMessageCount();
        System.out.println("Total messages = " + totalMessages);
        System.out.println("New messages = " + newMessages);
        System.out.println("-------------------------------");
      }

      if (uid == -1) {
        // Attributes & Flags for ALL messages ..
        Message[] msgs = ufolder.getMessagesByUID(1, UIDFolder.LASTUID);

        // Use a suitable FetchProfile
        FetchProfile fp = new FetchProfile();
        fp.add(FetchProfile.Item.ENVELOPE);
        fp.add(FetchProfile.Item.FLAGS);
        fp.add("X-Mailer");
        folder.fetch(msgs, fp);

        for (int i = 0; i < msgs.length; i++) {
          System.out.println("--------------------------");
          System.out.println("MESSAGE UID #" + ufolder.getUID(msgs[i]) ":");
          dumpEnvelope(msgs[i]);
          // dumpPart(msgs[i]);
        }
      else {
        System.out.println("Getting message UID: " + uid);
        Message m = ufolder.getMessageByUID(uid);
        if (m != null)
          dumpPart(m);
        else
          System.out.println("This Message does not exist on this folder");
      }

      folder.close(false);
      store.close();
    catch (Exception ex) {
      System.out.println("Oops, got exception! " + ex.getMessage());
      ex.printStackTrace();
    }
    System.exit(1);
  }

  public static void dumpPart(Part pthrows Exception {
    if (instanceof Message)
      dumpEnvelope((Messagep);

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

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

    Object o = p.getContent();
    if (instanceof String) {
      System.out.println("This is a String");
      System.out.println("---------------------------");
      System.out.println((Stringo);
    else if (instanceof Multipart) {
      System.out.println("This is a Multipart");
      System.out.println("---------------------------");
      Multipart mp = (Multiparto;
      int count = mp.getCount();
      for (int i = 0; i < count; i++)
        dumpPart(mp.getBodyPart(i));
    else if (instanceof Message) {
      System.out.println("This is a Nested Message");
      System.out.println("---------------------------");
      dumpPart((Parto);
    else if (instanceof InputStream) {
      System.out.println("This is just an input stream");
      System.out.println("---------------------------");
      InputStream is = (InputStreamo;
      int c;
      while ((c = is.read()) != -1)
        System.out.write(c);
    }
  }

  public static void dumpEnvelope(Message mthrows Exception {
    System.out.println("This is the message envelope");
    System.out.println("---------------------------");
    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.toString() "UNKNOWN"));

    // SIZE
    System.out.println("Size: " + m.getSize());

    // 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());

    // X-MAILER
    String[] hdrs = m.getHeader("X-Mailer");
    if (hdrs != null)
      System.out.println("X-Mailer: " + hdrs[0]);
    else
      System.out.println("X-Mailer NOT available");
  }
}

           
         
  














Related examples in the same category
1.Creates a message, retrieves a Transport from the session based on the type of the address and sends the message
2.Create a very simple text/plain message and sends it
3.Show information about and contents of messages
4.Get Message Size Line Count
5.Create a simple multipart/mixed message and sends it
6.How to construct and send an RFC822 (singlepart) message
7.How to construct and send a single part html message
8.Send an email message
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.