HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML
 

"What is JavaMail?"
Volume: 4 Issue: 10, p.36

	

Listing 1:

/*
* SendMessage.java
*/


import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;


/**
* This is copied almost directly from
* msgsendsample.java, by Max Spivak,
* with changes by Rachel Gollub
* ([email protected]).  More details
* are available in the accompanying
* article.
*/
public class SendMessage {


  public boolean send(MessageObject message) {
    //create some properties and get
    //the default Session
    Properties props = new Proper-
    ties();
    props.put("mail.smtp.host", mes-
    sage.host);
    // Uncomment this to debug
    //props.put("mail.debug", args[3]);


    Session session =
      Session.getDefaultInstance(props,
      null);
    session.setDebug(false); // true to
    debug


    try {
      // create a message
      Message msg = new MimeMessage(ses-
      sion);
      msg.setFrom
        (new InternetAddress(mes-
         sage.from));
      InternetAddress[] address =
        {new InternetAddress(mes-
         sage.to)};
      msg.setRecipients
        (Message.RecipientType.TO,
         address);
      msg.setSubject(message.subject);
      msg.setSentDate(new Date());
      msg.setText(replace
        (message.custom, message.text));


      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();
        } while ((ex = ((MessagingException)ex)
          .getNextException()) != null);
      return false;
    }
      return true;
    }


  /**
   * This is a simple replace method.  It
   * searches for the keywords, and uses
   * a StringBuffer to replace them.
   *
   * @param macros The keywords and values.
   * @param message The message to change.
   *
   * @return The changed message.
   */
  public String replace (Hashtable macros,
                         String message) {
    for (Enumeration e = macros.keys();
      e.hasMoreElements(); ) {
      int index = 0;
      String key = (String) e.nextElement();
      String value = (String) macros.get(key);
      while ((index =
        message.indexOf(key, index)) !=-1) {
        StringBuffer text =
          new StringBuffer(message);
        message = text.replace(index,
          index + key.length(), value)
          .toString();
        index += value.length();
      }
    }
    return message;
  }
}



/*
* MakeMessage.java
*/


import java.util.Hashtable;


/**
* This is a test class that creates some
* MessageObjects to send with SendMessage.
*
* @author Rachel Gollub ([email protected])
*/
public class MakeMessage {


  /**
   * The main method initializes the objects
   * and sends them.
   */
  public static void main(String args[]) {


    SendMessage message = new SendMessage();
    MessageObject object =
      makeObject("[email protected]",
                 "Rachel", "chocolate");
    message.send(object);
    object = makeObject("[email protected]",
                        "Jeremy", "chicken");
    message.send(object);
    object = makeObject("[email protected]",
                        "Miriam", "milk");
    message.send(object);
  }


  /**
   * This creates the actual MessageObject
   * for each recipient, filling it with
   * standard and custom values.
   */
  public static MessageObject makeObject
    (String to, String name, String food) {
    MessageObject object = new MessageObject();
    Hashtable macros = new Hashtable();
    macros.put("$firstname", name);
    macros.put("$favoritefood", food);


    object.to = to;
    object.custom = macros;
    object.text =
      "Dear $firstname,\n" +
      "\n" +
      "We'd like you to know that " +
      "$favoritefood is on sale this week!\n" +
      "\n" +
      "Sincerely,\n" +
      "The Management";


    object.subject = "SALE!";
    object.host = "pop.idiom.com";
    object.from = "[email protected]";


    return object;
  }
}



/*
* MessageObject.java
*/


import java.util.Hashtable;


/**
* This class holds message information.
*
* @author Rachel Gollub ([email protected])
*/
public class MessageObject {
  String to;
  String from;
  String host;
  String subject;
  String text;
  Hashtable custom;
}


Listing 2

/*
* MailPrinter.java
*/


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;


import java.util.Enumeration;
import java.util.Properties;


import javax.mail.Address;
import javax.mail.FetchProfile;
import javax.mail.Flags;
import javax.mail.Flags.Flag;
import javax.mail.Folder;
import javax.mail.Header;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;


/**
* This class monitors a given mailbox every 5
* minutes, and prints the contents to stdout.
* It will also optionally delete messages it
* reads.  More detailed comments are provided in
* the accompanying article.
*
* @author Rachel Gollub ([email protected])
*/
public class MailPrinter extends Thread {


  public static void main(String args[]) {
    // These args are <user>, <password>, <host>,
    // <delete?true:false>
    MailPrinter popThread =
      new MailPrinter(args[0], args[1],
                      args[2], args[3]);
    popThread.start();
  }


  String protocol = "pop3";
  String host;
  String user;
  String password;
  boolean delete = false;


  /**
   * This just initializes the global variables.
   */
  public MailPrinter(String pUser,
    String pPassword, String pHost,
    String pDelete) {
    user = pUser;
    password = pPassword;
    host = pHost;
    if (pDelete.toLowerCase().equals("true"))
      delete = true;
  }


  /**
   * The run() method makes a mailbox connection
   * every five minutes to check for mail.
   */
  public void run() {
    while (true) {
    doStore();
      try {
    Thread.sleep(300000);
      } catch (Exception e) {
    e.printStackTrace();
      }
    }
  }


  public void doStore() {
    Properties lProperties =
      System.getProperties();


    Session lSession =
      Session.getDefaultInstance
        (lProperties, null);
    // Set debug here
    lSession.setDebug(false);


    Store store = null;
    Folder folder = null;
    try {
      store = lSession.getStore(protocol);
    } catch (Exception e) {
      System.out.println
        ("Couldn't get store from protocol.");
      e.printStackTrace();
    }
    // Connect
    try {
      if (host != null || user != null
      || password != null)
    store.connect
      (host, user, password);
      else
    store.connect();
    } catch (Exception e) {
      System.out.println("Unable to connect.");
      e.printStackTrace();
    }


    // Open the Folder
    if (folder == null)
      try {
    folder = store.getDefaultFolder();
      } catch (Exception e) {
    System.out.println
      ("Couldn't get folder.");
    e.printStackTrace();
      }
    if (folder == null) {
      System.out.println("No default folder");
    }


    // Get the default folder
    try {
      folder = folder.getFolder("INBOX");
      if (folder == null) {
    System.out.println("Invalid folder");
      }


      if (folder != null) {
    folder.open(Folder.READ_WRITE);
    int lTotalMessages =
      folder.getMessageCount();


    if (lTotalMessages == 0) {
      System.out.println("Empty folder");
      folder.close(false);
      folder = null;
      store.close();
    }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }


    // Get and process messages
    if (folder != null) {
      try {
    Message[] messages =
      folder.getMessages();


    for (int i = 0;
      i < messages.length; i++) {
      if (filter(messages[i])) {
        if (delete)
          messages[i].setFlag
            (Flags.Flag.DELETED, true);
      }
    }
    folder.close(true);
    store.close();
      } catch (Exception e) {
    e.printStackTrace();
      }
    }
  }


  /**
   * The filter() method tries to figure out the
   * message type, and recursively sends
   * multi-part parts through the filter.
   *
   * @param part The message part.
   *
   * @return True iff successful.
   */
  public boolean filter(Part part) {


    Object o = null;


    try {
      for (Enumeration e = part.getAllHeaders();
        e.hasMoreElements(); ) {
        Header header =
          (Header) e.nextElement();
        System.out.println(header.getName() +
          ": " + header.getValue());
      }
      System.out.println("\n");
      o = part.getContent();
    } catch (Exception e) {
      System.out.println
        ("Couldn't get content.");
      return false;
    }
    if (o instanceof String) {
      String lMessage = (String) o;
      System.out.println(lMessage);
      return true;
    } else if (o instanceof Multipart) {
      Multipart lPart = (Multipart)o;
      try {
    int count = lPart.getCount();
    for (int i = 0; i < count; i++)
      return filter(lPart.getBodyPart(i));
      } catch (Exception e) {
    System.out.println
      ("Couldn't access parts.");
    e.printStackTrace();
      }
    } else if (o instanceof Message) {
      return filter((Part)o);
    } else if (o instanceof InputStream) {
      BufferedReader lReader = new BufferedReader
    (new InputStreamReader((InputStream) o));
      int c;
      StringBuffer lBuffer = new StringBuffer();
      try {
    while ((c = lReader.read()) != -1)
      lBuffer.append((char) c);
    lReader.close();
      } catch (Exception e) {
    System.out.println("Read error.");
    e.printStackTrace();
      }
      System.out.println(lBuffer.toString());
      return true;
    }
    return false;
  }


}

      
 

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.