Java Tutorial/Email/Email Message

Материал из Java эксперт
Версия от 15:23, 31 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

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 = (UIDFolder) folder;
      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 p) throws Exception {
    if (p instanceof Message)
      dumpEnvelope((Message) p);
    /*
     * 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 (o instanceof String) {
      System.out.println("This is a String");
      System.out.println("---------------------------");
      System.out.println((String) o);
    } else if (o instanceof Multipart) {
      System.out.println("This is a Multipart");
      System.out.println("---------------------------");
      Multipart mp = (Multipart) o;
      int count = mp.getCount();
      for (int i = 0; i < count; i++)
        dumpPart(mp.getBodyPart(i));
    } else if (o instanceof Message) {
      System.out.println("This is a Nested Message");
      System.out.println("---------------------------");
      dumpPart((Part) o);
    } else if (o instanceof InputStream) {
      System.out.println("This is just an input stream");
      System.out.println("---------------------------");
      InputStream is = (InputStream) o;
      int c;
      while ((c = is.read()) != -1)
        System.out.write(c);
    }
  }
  public static void dumpEnvelope(Message m) throws 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");
  }
}





Create a simple multipart/mixed message and sends it

/*
 * @(#)msgmultisendsample.java  1.14 03/04/22
 *
 * Copyright 1996-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.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
// import javax.activation.*;
/**
 * msgmultisendsample creates a simple multipart/mixed message and sends it.
 * Both body parts are text/plain.
 * <P>
 * usage: <code>java msgmultisendsample <i>to from smtp true|false</i></code>
 * where <i>to</i> and <i>from</i> are the destination and origin email
 * addresses, respectively, and <i>smtp</i> is the hostname of the machine that
 * has smtp server running. The last parameter either turns on or turns off
 * debugging during sending.
 * 
 * @author Max Spivak
 */
public class MainClass {
  static String msgText1 = "This is a message body.\nHere"s line two.";
  static String msgText2 = "This is the text in the message attachment.";
  public static void main(String[] args) {
    if (args.length != 4) {
      System.out.println("usage: java msgmultisend <to> <from> <smtp> true|false");
      return;
    }
    String to = args[0];
    String from = args[1];
    String host = args[2];
    boolean debug = Boolean.valueOf(args[3]).booleanValue();
    // create some properties and get the default Session
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    Session session = Session.getInstance(props, null);
    session.setDebug(debug);
    try {
      // create a message
      MimeMessage msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress(from));
      InternetAddress[] address = { new InternetAddress(to) };
      msg.setRecipients(Message.RecipientType.TO, address);
      msg.setSubject("JavaMail APIs Multipart Test");
      msg.setSentDate(new Date());
      // create and fill the first message part
      MimeBodyPart mbp1 = new MimeBodyPart();
      mbp1.setText(msgText1);
      // create and fill the second message part
      MimeBodyPart mbp2 = new MimeBodyPart();
      // Use setText(text, charset), to show it off !
      mbp2.setText(msgText2, "us-ascii");
      // create the Multipart and its parts to it
      Multipart mp = new MimeMultipart();
      mp.addBodyPart(mbp1);
      mp.addBodyPart(mbp2);
      // add the Multipart to the message
      msg.setContent(mp);
      // send the message
      Transport.send(msg);
    } catch (MessagingException mex) {
      mex.printStackTrace();
      Exception ex = null;
      if ((ex = mex.getNextException()) != null) {
        ex.printStackTrace();
      }
    }
  }
}





Create a very simple text/plain message and sends it

/*
 * @(#)msgsendsample.java 1.19 03/04/22
 *
 * Copyright 1996-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.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
// import javax.activation.*;
/**
 * msgsendsample creates a very simple text/plain message and sends it.
 * <P>
 * usage: <code>java msgsendsample <i>to from smtphost true|false</i></code>
 * where <i>to</i> and <i>from</i> are the destination and origin email
 * addresses, respectively, and <i>smtphost</i> is the hostname of the machine
 * that has the smtp server running. The last parameter either turns on or turns
 * off debugging during sending.
 * 
 * @author Max Spivak
 */
public class MainClass {
  static String msgText = "This is a message body.\nHere"s the second line.";
  public static void main(String[] args) {
    if (args.length != 4) {
      usage();
      System.exit(1);
    }
    System.out.println();
    String to = args[0];
    String from = args[1];
    String host = args[2];
    boolean debug = Boolean.valueOf(args[3]).booleanValue();
    // create some properties and get the default Session
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    if (debug)
      props.put("mail.debug", args[3]);
    Session session = Session.getInstance(props, null);
    session.setDebug(debug);
    try {
      // create a message
      Message msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress(from));
      InternetAddress[] address = { new InternetAddress(args[0]) };
      msg.setRecipients(Message.RecipientType.TO, address);
      msg.setSubject("JavaMail APIs Test");
      msg.setSentDate(new Date());
      // If the desired charset is known, you can use
      // setText(text, charset)
      msg.setText(msgText);
      Transport.send(msg);
    } catch (MessagingException mex) {
      System.out.println("\n--Exception handling in msgsendsample.java");
      mex.printStackTrace();
      System.out.println();
      Exception ex = mex;
      do {
        if (ex instanceof SendFailedException) {
          SendFailedException sfex = (SendFailedException) ex;
          Address[] invalid = sfex.getInvalidAddresses();
          if (invalid != null) {
            System.out.println("    ** Invalid Addresses");
            if (invalid != null) {
              for (int i = 0; i < invalid.length; i++)
                System.out.println("         " + invalid[i]);
            }
          }
          Address[] validUnsent = sfex.getValidUnsentAddresses();
          if (validUnsent != null) {
            System.out.println("    ** ValidUnsent Addresses");
            if (validUnsent != null) {
              for (int i = 0; i < validUnsent.length; i++)
                System.out.println("         " + validUnsent[i]);
            }
          }
          Address[] validSent = sfex.getValidSentAddresses();
          if (validSent != null) {
            System.out.println("    ** ValidSent Addresses");
            if (validSent != null) {
              for (int i = 0; i < validSent.length; i++)
                System.out.println("         " + validSent[i]);
            }
          }
        }
        System.out.println();
        if (ex instanceof MessagingException)
          ex = ((MessagingException) ex).getNextException();
        else
          ex = null;
      } while (ex != null);
    }
  }
  private static void usage() {
    System.out.println("usage: java msgsendsample <to> <from> <smtp> true|false");
  }
}





Creates a message, retrieves a Transport from the session based on the type of the address and sends the message

/*
 * @(#)transport.java 1.13 06/04/17
 *
 * Copyright 1997-2006 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.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.event.ConnectionEvent;
import javax.mail.event.ConnectionListener;
import javax.mail.event.TransportEvent;
import javax.mail.event.TransportListener;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
// import javax.activation.*;
/**
 * transport is a simple program that creates a message, explicitly retrieves a
 * Transport from the session based on the type of the address (it"s
 * InternetAddress, so SMTP will be used) and sends the message.
 * 
 * usage: <code>java transport <i>"toaddr1[, toaddr2]*"  from smtphost 
 * true|false</i></code><br>
 * where <i>to</i> and <i>from</i> are the destination and origin email
 * addresses, respectively, and <i>smtphost</i> is the hostname of the machine
 * that has the smtp server running. The <i>to</i> addresses can be either a
 * single email address or a comma-separated list of email addresses in quotes,
 * i.e. "joe@machine, jane, max@server.ru" The last parameter either turns on
 * or turns off debugging during sending.
 * 
 * @author Max Spivak
 */
public class transport implements ConnectionListener, TransportListener {
  static String msgText = "This is a message body.\nHere"s the second line.";
  static String msgText2 = "\nThis was sent by transport.java demo program.";
  public static void main(String[] args) {
    Properties props = new Properties();
    // parse the arguments
    InternetAddress[] addrs = null;
    InternetAddress from;
    boolean debug = false;
    if (args.length != 4) {
      usage();
      return;
    } else {
      props.put("mail.smtp.host", args[2]);
      if (args[3].equals("true")) {
        debug = true;
      } else if (args[3].equals("false")) {
        debug = false;
      } else {
        usage();
        return;
      }
      // parse the destination addresses
      try {
        addrs = InternetAddress.parse(args[0], false);
        from = new InternetAddress(args[1]);
      } catch (AddressException aex) {
        System.out.println("Invalid Address");
        aex.printStackTrace();
        return;
      }
    }
    // create some properties and get a Session
    Session session = Session.getInstance(props, null);
    session.setDebug(debug);
    transport t = new transport();
    t.go(session, addrs, from);
  }
  public transport() {
  }
  public void go(Session session, InternetAddress[] toAddr, InternetAddress from) {
    Transport trans = null;
    try {
      // create a message
      Message msg = new MimeMessage(session);
      msg.setFrom(from);
      msg.setRecipients(Message.RecipientType.TO, toAddr);
      msg.setSubject("JavaMail APIs transport.java Test");
      msg.setSentDate(new Date()); // Date: header
      msg.setContent(msgText + msgText2, "text/plain");
      msg.saveChanges();
      // get the smtp transport for the address
      trans = session.getTransport(toAddr[0]);
      // register ourselves as listener for ConnectionEvents
      // and TransportEvents
      trans.addConnectionListener(this);
      trans.addTransportListener(this);
      // connect the transport
      trans.connect();
      // send the message
      trans.sendMessage(msg, toAddr);
      // give the EventQueue enough time to fire its events
      try {
        Thread.sleep(5);
      } catch (InterruptedException e) {
      }
    } catch (MessagingException mex) {
      // give the EventQueue enough time to fire its events
      try {
        Thread.sleep(5);
      } catch (InterruptedException e) {
      }
      mex.printStackTrace();
      System.out.println();
      Exception ex = mex;
      do {
        if (ex instanceof SendFailedException) {
          SendFailedException sfex = (SendFailedException) ex;
          Address[] invalid = sfex.getInvalidAddresses();
          if (invalid != null) {
            System.out.println("    ** Invalid Addresses");
            if (invalid != null) {
              for (int i = 0; i < invalid.length; i++)
                System.out.println("         " + invalid[i]);
            }
          }
          Address[] validUnsent = sfex.getValidUnsentAddresses();
          if (validUnsent != null) {
            System.out.println("    ** ValidUnsent Addresses");
            if (validUnsent != null) {
              for (int i = 0; i < validUnsent.length; i++)
                System.out.println("         " + validUnsent[i]);
            }
          }
          Address[] validSent = sfex.getValidSentAddresses();
          if (validSent != null) {
            System.out.println("    ** ValidSent Addresses");
            if (validSent != null) {
              for (int i = 0; i < validSent.length; i++)
                System.out.println("         " + validSent[i]);
            }
          }
        }
        System.out.println();
        if (ex instanceof MessagingException)
          ex = ((MessagingException) ex).getNextException();
        else
          ex = null;
      } while (ex != null);
    } finally {
      try {
        // close the transport
        trans.close();
      } catch (MessagingException mex) { /* ignore */
      }
    }
  }
  // implement ConnectionListener interface
  public void opened(ConnectionEvent e) {
    System.out.println(">>> ConnectionListener.opened()");
  }
  public void disconnected(ConnectionEvent e) {
  }
  public void closed(ConnectionEvent e) {
    System.out.println(">>> ConnectionListener.closed()");
  }
  // implement TransportListener interface
  public void messageDelivered(TransportEvent e) {
    System.out.print(">>> TransportListener.messageDelivered().");
    System.out.println(" Valid Addresses:");
    Address[] valid = e.getValidSentAddresses();
    if (valid != null) {
      for (int i = 0; i < valid.length; i++)
        System.out.println("    " + valid[i]);
    }
  }
  public void messageNotDelivered(TransportEvent e) {
    System.out.print(">>> TransportListener.messageNotDelivered().");
    System.out.println(" Invalid Addresses:");
    Address[] invalid = e.getInvalidAddresses();
    if (invalid != null) {
      for (int i = 0; i < invalid.length; i++)
        System.out.println("    " + invalid[i]);
    }
  }
  public void messagePartiallyDelivered(TransportEvent e) {
    // SMTPTransport doesn"t partially deliver msgs
  }
  private static void usage() {
    System.out
        .println("usage: java transport \"<to1>[, <to2>]*\" <from> <smtp> true|false\nexample: java transport \"joe@machine, jane\" senderaddr smtphost false");
  }
}





Get Message Size Line Count

import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
public class MainClass {
  public static void main(String[] args) throws Exception {
    URLName server = new URLName("protocol://username@host/foldername");
    Session session = Session.getDefaultInstance(new Properties(), new MailAuthenticator());
    Folder folder = session.getFolder(server);
    if (folder == null) {
      System.out.println("Folder " + server.getFile() + " not found.");
      System.exit(1);
    }
    folder.open(Folder.READ_ONLY);
    Message[] messages = folder.getMessages();
    for (int i = 0; i < messages.length; i++) {
      System.out.println(messages[i].getSize() + " bytes long.");
      System.out.println(messages[i].getLineCount() + " lines.");
    }
    folder.close(false);
  }
}
class MailAuthenticator extends Authenticator {
  public MailAuthenticator() {
  }
  public PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication("username", "password");
  }
}





How to construct and send an RFC822 (singlepart) message

/*
 * @(#)smtpsend.java  1.5 05/12/09
 *
 * Copyright 1997-2005 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.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import com.sun.mail.smtp.SMTPAddressFailedException;
import com.sun.mail.smtp.SMTPAddressSucceededException;
import com.sun.mail.smtp.SMTPSendFailedException;
import com.sun.mail.smtp.SMTPTransport;
/**
 * Demo app that shows how to construct and send an RFC822 (singlepart) message.
 * 
 * XXX - allow more than one recipient on the command line
 * 
 * This is just a variant of msgsend.java that demonstrates use of some
 * SMTP-specific features.
 * 
 * @author Max Spivak
 * @author Bill Shannon
 */
public class smtpsend {
  public static void main(String[] argv) {
    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;
    String mailer = "smtpsend";
    String file = null;
    String protocol = null, host = null, user = null, password = null;
    String record = null; // name of folder in which to record mail
    boolean debug = false;
    boolean verbose = false;
    boolean auth = false;
    boolean ssl = false;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    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("-M")) {
        mailhost = argv[++optind];
      } else if (argv[optind].equals("-f")) {
        record = argv[++optind];
      } else if (argv[optind].equals("-a")) {
        file = argv[++optind];
      } else if (argv[optind].equals("-s")) {
        subject = argv[++optind];
      } else if (argv[optind].equals("-o")) { // originator
        from = argv[++optind];
      } else if (argv[optind].equals("-c")) {
        cc = argv[++optind];
      } else if (argv[optind].equals("-b")) {
        bcc = argv[++optind];
      } else if (argv[optind].equals("-L")) {
        url = argv[++optind];
      } else if (argv[optind].equals("-d")) {
        debug = true;
      } else if (argv[optind].equals("-v")) {
        verbose = true;
      } else if (argv[optind].equals("-A")) {
        auth = true;
      } else if (argv[optind].equals("-S")) {
        ssl = true;
      } else if (argv[optind].equals("--")) {
        optind++;
        break;
      } else if (argv[optind].startsWith("-")) {
        System.out
            .println("Usage: smtpsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
        System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
        System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [-a attach-file]");
        System.out.println("\t[-v] [-A] [-S] [address]");
        System.exit(1);
      } else {
        break;
      }
    }
    try {
      if (optind < argv.length) {
        // XXX - concatenate all remaining arguments
        to = argv[optind];
        System.out.println("To: " + to);
      } else {
        System.out.print("To: ");
        System.out.flush();
        to = in.readLine();
      }
      if (subject == null) {
        System.out.print("Subject: ");
        System.out.flush();
        subject = in.readLine();
      } else {
        System.out.println("Subject: " + subject);
      }
      Properties props = System.getProperties();
      if (mailhost != null)
        props.put("mail.smtp.host", mailhost);
      if (auth)
        props.put("mail.smtp.auth", "true");
      // Get a Session object
      Session session = Session.getInstance(props, null);
      if (debug)
        session.setDebug(true);
      // construct the message
      Message msg = new MimeMessage(session);
      if (from != null)
        msg.setFrom(new InternetAddress(from));
      else
        msg.setFrom();
      msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
      if (cc != null)
        msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
      if (bcc != null)
        msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
      msg.setSubject(subject);
      String text = collect(in);
      if (file != null) {
        // Attach the specified file.
        // We need a multipart message to hold the attachment.
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(text);
        MimeBodyPart mbp2 = new MimeBodyPart();
        mbp2.attachFile(file);
        MimeMultipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
        msg.setContent(mp);
      } else {
        // If the desired charset is known, you can use
        // setText(text, charset)
        msg.setText(text);
      }
      msg.setHeader("X-Mailer", mailer);
      msg.setSentDate(new Date());
      // send the thing off
      /*
       * The simple way to send a message is this:
       * 
       * Transport.send(msg);
       * 
       * But we"re going to use some SMTP-specific features for demonstration
       * purposes so we need to manage the Transport object explicitly.
       */
      SMTPTransport t = (SMTPTransport) session.getTransport(ssl ? "smtps" : "smtp");
      try {
        if (auth)
          t.connect(mailhost, user, password);
        else
          t.connect();
        t.sendMessage(msg, msg.getAllRecipients());
      } finally {
        if (verbose)
          System.out.println("Response: " + t.getLastServerResponse());
        t.close();
      }
      System.out.println("\nMail was sent successfully.");
      // Keep a copy, if requested.
      if (record != null) {
        // 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();
        }
        // Get record Folder. Create if it does not exist.
        Folder folder = store.getFolder(record);
        if (folder == null) {
          System.err.println("Can"t get record folder.");
          System.exit(1);
        }
        if (!folder.exists())
          folder.create(Folder.HOLDS_MESSAGES);
        Message[] msgs = new Message[1];
        msgs[0] = msg;
        folder.appendMessages(msgs);
        System.out.println("Mail was recorded successfully.");
      }
    } catch (Exception e) {
      if (e instanceof SendFailedException) {
        MessagingException sfe = (MessagingException) e;
        if (sfe instanceof SMTPSendFailedException) {
          SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe;
          System.out.println("SMTP SEND FAILED:");
          if (verbose)
            System.out.println(ssfe.toString());
          System.out.println("  Command: " + ssfe.getCommand());
          System.out.println("  RetCode: " + ssfe.getReturnCode());
          System.out.println("  Response: " + ssfe.getMessage());
        } else {
          if (verbose)
            System.out.println("Send failed: " + sfe.toString());
        }
        Exception ne;
        while ((ne = sfe.getNextException()) != null && ne instanceof MessagingException) {
          sfe = (MessagingException) ne;
          if (sfe instanceof SMTPAddressFailedException) {
            SMTPAddressFailedException ssfe = (SMTPAddressFailedException) sfe;
            System.out.println("ADDRESS FAILED:");
            if (verbose)
              System.out.println(ssfe.toString());
            System.out.println("  Address: " + ssfe.getAddress());
            System.out.println("  Command: " + ssfe.getCommand());
            System.out.println("  RetCode: " + ssfe.getReturnCode());
            System.out.println("  Response: " + ssfe.getMessage());
          } else if (sfe instanceof SMTPAddressSucceededException) {
            System.out.println("ADDRESS SUCCEEDED:");
            SMTPAddressSucceededException ssfe = (SMTPAddressSucceededException) sfe;
            if (verbose)
              System.out.println(ssfe.toString());
            System.out.println("  Address: " + ssfe.getAddress());
            System.out.println("  Command: " + ssfe.getCommand());
            System.out.println("  RetCode: " + ssfe.getReturnCode());
            System.out.println("  Response: " + ssfe.getMessage());
          }
        }
      } else {
        System.out.println("Got Exception: " + e);
        if (verbose)
          e.printStackTrace();
      }
    }
  }
  public static String collect(BufferedReader in) throws IOException {
    String line;
    StringBuffer sb = new StringBuffer();
    while ((line = in.readLine()) != null) {
      sb.append(line);
      sb.append("\n");
    }
    return sb.toString();
  }
}





How to construct and send a single part html message

/*
 * @(#)sendhtml.java  1.10 05/08/17
 *
 * Copyright 1998-2005 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.*;
import java.util.Properties;
import java.util.Date;
import javax.mail.*;
import javax.activation.*;
import javax.mail.internet.*;
import javax.mail.util.*;
/**
 * Demo app that shows how to construct and send a single part html message.
 * Note that the same basic technique can be used to send data of any type.
 * 
 * @author John Mani
 * @author Bill Shannon
 * @author Max Spivak
 */
public class sendhtml {
  public static void main(String[] argv) {
    new sendhtml(argv);
  }
  public sendhtml(String[] argv) {
    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;
    String mailer = "sendhtml";
    String protocol = null, host = null, user = null, password = null;
    String record = null; // name of folder in which to record mail
    boolean debug = false;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    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("-M")) {
        mailhost = argv[++optind];
      } else if (argv[optind].equals("-f")) {
        record = argv[++optind];
      } else if (argv[optind].equals("-s")) {
        subject = argv[++optind];
      } else if (argv[optind].equals("-o")) { // originator
        from = argv[++optind];
      } else if (argv[optind].equals("-c")) {
        cc = argv[++optind];
      } else if (argv[optind].equals("-b")) {
        bcc = argv[++optind];
      } else if (argv[optind].equals("-L")) {
        url = argv[++optind];
      } else if (argv[optind].equals("-d")) {
        debug = true;
      } else if (argv[optind].equals("--")) {
        optind++;
        break;
      } else if (argv[optind].startsWith("-")) {
        System.out
            .println("Usage: sendhtml [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
        System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
        System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [address]");
        System.exit(1);
      } else {
        break;
      }
    }
    try {
      if (optind < argv.length) {
        // XXX - concatenate all remaining arguments
        to = argv[optind];
        System.out.println("To: " + to);
      } else {
        System.out.print("To: ");
        System.out.flush();
        to = in.readLine();
      }
      if (subject == null) {
        System.out.print("Subject: ");
        System.out.flush();
        subject = in.readLine();
      } else {
        System.out.println("Subject: " + subject);
      }
      Properties props = System.getProperties();
      // XXX - could use Session.getTransport() and Transport.connect()
      // XXX - assume we"re using SMTP
      if (mailhost != null)
        props.put("mail.smtp.host", mailhost);
      // Get a Session object
      Session session = Session.getInstance(props, null);
      if (debug)
        session.setDebug(true);
      // construct the message
      Message msg = new MimeMessage(session);
      if (from != null)
        msg.setFrom(new InternetAddress(from));
      else
        msg.setFrom();
      msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
      if (cc != null)
        msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
      if (bcc != null)
        msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
      msg.setSubject(subject);
      collect(in, msg);
      msg.setHeader("X-Mailer", mailer);
      msg.setSentDate(new Date());
      // send the thing off
      Transport.send(msg);
      System.out.println("\nMail was sent successfully.");
      // Keep a copy, if requested.
      if (record != null) {
        // 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();
        }
        // Get record Folder. Create if it does not exist.
        Folder folder = store.getFolder(record);
        if (folder == null) {
          System.err.println("Can"t get record folder.");
          System.exit(1);
        }
        if (!folder.exists())
          folder.create(Folder.HOLDS_MESSAGES);
        Message[] msgs = new Message[1];
        msgs[0] = msg;
        folder.appendMessages(msgs);
        System.out.println("Mail was recorded successfully.");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public void collect(BufferedReader in, Message msg) throws MessagingException, IOException {
    String line;
    String subject = msg.getSubject();
    StringBuffer sb = new StringBuffer();
    sb.append("<HTML>\n");
    sb.append("<HEAD>\n");
    sb.append("<TITLE>\n");
    sb.append(subject + "\n");
    sb.append("</TITLE>\n");
    sb.append("</HEAD>\n");
    sb.append("<BODY>\n");
    sb.append("<H1>" + subject + "</H1>" + "\n");
    while ((line = in.readLine()) != null) {
      sb.append(line);
      sb.append("\n");
    }
    sb.append("</BODY>\n");
    sb.append("</HTML>\n");
    msg.setDataHandler(new DataHandler(new ByteArrayDataSource(sb.toString(), "text/html")));
  }
}





Show information about and contents of messages

/*
 * @(#)msgshow.java 1.33 05/12/09
 *
 * Copyright 1997-2005 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.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
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.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.event.StoreEvent;
import javax.mail.event.StoreListener;
import javax.mail.internet.ContentType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.ParseException;
// import javax.activation.*;
/*
 * Demo app that exercises the Message interfaces. Show information about and
 * contents of messages.
 * 
 * @author John Mani @author Bill Shannon
 */
public class MainClass {
  static String protocol;
  static String host = null;
  static String user = null;
  static String password = null;
  static String mbox = null;
  static String url = null;
  static int port = -1;
  static boolean verbose = false;
  static boolean debug = false;
  static boolean showStructure = false;
  static boolean showMessage = false;
  static boolean showAlert = false;
  static boolean saveAttachments = false;
  static int attnum = 1;
  public static void main(String argv[]) {
    int msgnum = -1;
    int optind;
    InputStream msgStream = System.in;
    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("-D")) {
        debug = true;
      } else if (argv[optind].equals("-f")) {
        mbox = argv[++optind];
      } else if (argv[optind].equals("-L")) {
        url = argv[++optind];
      } else if (argv[optind].equals("-p")) {
        port = Integer.parseInt(argv[++optind]);
      } else if (argv[optind].equals("-s")) {
        showStructure = true;
      } else if (argv[optind].equals("-S")) {
        saveAttachments = true;
      } else if (argv[optind].equals("-m")) {
        showMessage = true;
      } else if (argv[optind].equals("-a")) {
        showAlert = true;
      } else if (argv[optind].equals("--")) {
        optind++;
        break;
      } else if (argv[optind].startsWith("-")) {
        System.out.println("Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]");
        System.out.println("\t[-P password] [-f mailbox] [msgnum] [-v] [-D] [-s] [-S] [-a]");
        System.out.println("or     msgshow -m [-v] [-D] [-s] [-S] [-f msg-file]");
        System.exit(1);
      } else {
        break;
      }
    }
    try {
      if (optind < argv.length)
        msgnum = Integer.parseInt(argv[optind]);
      // Get a Properties object
      Properties props = System.getProperties();
      // Get a Session object
      Session session = Session.getInstance(props, null);
      session.setDebug(debug);
      if (showMessage) {
        MimeMessage msg;
        if (mbox != null)
          msg = new MimeMessage(session, new BufferedInputStream(new FileInputStream(mbox)));
        else
          msg = new MimeMessage(session, msgStream);
        dumpPart(msg);
        System.exit(0);
      }
      // Get a Store object
      Store store = null;
      if (url != null) {
        URLName urln = new URLName(url);
        store = session.getStore(urln);
        if (showAlert) {
          store.addStoreListener(new StoreListener() {
            public void notification(StoreEvent e) {
              String s;
              if (e.getMessageType() == StoreEvent.ALERT)
                s = "ALERT: ";
              else
                s = "NOTICE: ";
              System.out.println(s + e.getMessage());
            }
          });
        }
        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, port, user, password);
        else
          store.connect();
      }
      // Open the Folder
      Folder folder = store.getDefaultFolder();
      if (folder == null) {
        System.out.println("No default folder");
        System.exit(1);
      }
      if (mbox == null)
        mbox = "INBOX";
      folder = folder.getFolder(mbox);
      if (folder == null) {
        System.out.println("Invalid folder");
        System.exit(1);
      }
      // try to open read/write and if that fails try read-only
      try {
        folder.open(Folder.READ_WRITE);
      } catch (MessagingException ex) {
        folder.open(Folder.READ_ONLY);
      }
      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 (msgnum == -1) {
        // Attributes & Flags for all messages ..
        Message[] msgs = folder.getMessages();
        // 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 #" + (i + 1) + ":");
          dumpEnvelope(msgs[i]);
          // dumpPart(msgs[i]);
        }
      } else {
        System.out.println("Getting message number: " + msgnum);
        Message m = null;
        try {
          m = folder.getMessage(msgnum);
          dumpPart(m);
        } catch (IndexOutOfBoundsException iex) {
          System.out.println("Message number out of range");
        }
      }
      folder.close(false);
      store.close();
    } catch (Exception ex) {
      System.out.println("Oops, got exception! " + ex.getMessage());
      ex.printStackTrace();
      System.exit(1);
    }
    System.exit(0);
  }
  public static void dumpPart(Part p) throws Exception {
    if (p instanceof Message)
      dumpEnvelope((Message) p);
    /**
     * Dump input stream ..
     * 
     * InputStream is = p.getInputStream(); // If "is" is not already buffered,
     * wrap a BufferedInputStream // around it. if (!(is instanceof
     * BufferedInputStream)) is = new BufferedInputStream(is); int c; while ((c =
     * is.read()) != -1) System.out.write(c);
     * 
     */
    String ct = p.getContentType();
    try {
      pr("CONTENT-TYPE: " + (new ContentType(ct)).toString());
    } catch (ParseException pex) {
      pr("BAD CONTENT-TYPE: " + ct);
    }
    String filename = p.getFileName();
    if (filename != null)
      pr("FILENAME: " + filename);
    /*
     * Using isMimeType to determine the content type avoids fetching the actual
     * content data until we need it.
     */
    if (p.isMimeType("text/plain")) {
      pr("This is plain text");
      pr("---------------------------");
      if (!showStructure && !saveAttachments)
        System.out.println((String) p.getContent());
    } else if (p.isMimeType("multipart/*")) {
      pr("This is a Multipart");
      pr("---------------------------");
      Multipart mp = (Multipart) p.getContent();
      level++;
      int count = mp.getCount();
      for (int i = 0; i < count; i++)
        dumpPart(mp.getBodyPart(i));
      level--;
    } else if (p.isMimeType("message/rfc822")) {
      pr("This is a Nested Message");
      pr("---------------------------");
      level++;
      dumpPart((Part) p.getContent());
      level--;
    } else {
      if (!showStructure && !saveAttachments) {
        /*
         * If we actually want to see the data, and it"s not a MIME type we
         * know, fetch it and check its Java type.
         */
        Object o = p.getContent();
        if (o instanceof String) {
          pr("This is a string");
          pr("---------------------------");
          System.out.println((String) o);
        } else if (o instanceof InputStream) {
          pr("This is just an input stream");
          pr("---------------------------");
          InputStream is = (InputStream) o;
          int c;
          while ((c = is.read()) != -1)
            System.out.write(c);
        } else {
          pr("This is an unknown type");
          pr("---------------------------");
          pr(o.toString());
        }
      } else {
        // just a separator
        pr("---------------------------");
      }
    }
    /*
     * If we"re saving attachments, write out anything that looks like an
     * attachment into an appropriately named file. Don"t overwrite existing
     * files to prevent mistakes.
     */
    if (saveAttachments && level != 0 && !p.isMimeType("multipart/*")) {
      String disp = p.getDisposition();
      // many mailers don"t include a Content-Disposition
      if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) {
        if (filename == null)
          filename = "Attachment" + attnum++;
        pr("Saving attachment to file " + filename);
        try {
          File f = new File(filename);
          if (f.exists())
            // XXX - could try a series of names
            throw new IOException("file exists");
          ((MimeBodyPart) p).saveFile(f);
        } catch (IOException ex) {
          pr("Failed to save attachment: " + ex);
        }
        pr("---------------------------");
      }
    }
  }
  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());
        InternetAddress ia = (InternetAddress) a[j];
        if (ia.isGroup()) {
          InternetAddress[] aa = ia.getGroup(false);
          for (int k = 0; k < aa.length; k++)
            pr("  GROUP: " + aa[k].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");
  }
  static String indentStr = "                                               ";
  static int level = 0;
  /**
   * Print a, possibly indented, string.
   */
  public static void pr(String s) {
    if (showStructure)
      System.out.print(indentStr.substring(0, level * 2));
    System.out.println(s);
  }
}