A mail program sends and receives mail messages to/from a mail server. In this example, we use JMS as the mail server and mail messages are TextMessage's. The sender and recipient of mail messages are string properties of the message header.Below is the source code for the Mail class:
To send messages, the program requires two command line parameters:package mail; import java.util.Date; import javax.naming.InitialContext; import javax.jms.Queue; import javax.jms.Session; import javax.jms.Message; import javax.jms.TextMessage; import javax.jms.QueueSender; import javax.jms.QueueSession; import javax.jms.QueueReceiver; import javax.jms.QueueConnection; import javax.jms.QueueConnectionFactory; /** This class ilustrates a very simple mail application, which can read and send mail messages. */ public class Mail { public static void main(String[] args) throws Exception { | // create sender and receiver | InitialContext ctx = new InitialContext(); | QueueConnectionFactory factory = (QueueConnectionFactory) | ctx.lookup("queue/connectionFactory"); | Queue queue = (Queue) ctx.lookup("queue/queue0"); | QueueConnection conn = factory.createQueueConnection(); | QueueSession session = conn.createQueueSession(false, | Session.AUTO_ACKNOWLEDGE); | conn.start(); | | // first arg is recipient, second arg is message | if (args.length == 2) | { | | QueueSender sender = session.createSender(queue); | | TextMessage msg = session.createTextMessage(args[1]); | | msg.setStringProperty("sender", System.getProperty("user.name")); | | msg.setStringProperty("to", args[0]); | | msg.setStringProperty("date", new Date().toString()); | | sender.send(msg); | } | else | { | | String selector = "to = '" + System.getProperty("user.name") + "'"; | | QueueReceiver receiver = session.createReceiver(queue, selector); | | TextMessage msg = (TextMessage) receiver.receive(500); | | if (msg != null) | | { | | | System.out.println("From: " + msg.getStringProperty("sender")); | | | System.out.println("To: " + msg.getStringProperty("to")); | | | System.out.println("Date: " + msg.getStringProperty("date")); | | | System.out.println("\n" + msg.getText()); | | } | | else | | { | | | System.out.println("no messages"); | | } | } } }If run with no argument, the program assumes the current user wants to receive a mail message. To avoid messages from other users, the program sets the following selector:
- The recipient. This is the user name of the receiver of the message.
- The message itself. This is a short text string with the mail message.
"to = '" + System.getProperty("user.name") + "'";If a message is available on the queue, which matches this message selector, we receive a message from the queue and print it. If no messages are currently on the queue for the current user, we simply print "no messages".
Copyright © 2000-2003, Novell, Inc. All rights reserved. |