JavaMail starts quickly
Summary This article introduces the creation of Java-based Email applications. If you want to create your own Email client application instead of Microsoft Outlook, or create a web-based email system to call the hotmail, then you can start here. From a different point of view of JavaMail, this article gives a conversation Email client application. In JavaMail, you can find the API and its implementation, so that you have developed a full-time Email client application. "Email Client Application" references Microsoft Outlook ideas; however, you can write your own Outlook to replace. However, an email client program does not have to reside on a client machine. In fact, it can be a servlet or EJB running on the remote server, and the end user can send up their email through a web browser. In the author's own pet project, a voice client uses a voice client to read the message received. It is the description of the author in "Talking Java!" (There will be more introductions later). JavaMail software is now installed and configured. Installation If you are using Java2 Enterprise (J2EE) 1.3, it has been with JavaMail, so no additional installation is required. But if you are using the Java2 Standard Edition (J2SE) 1.1.7 and later version, then if you want your application to send and receive email, download and install the following two applications: L, JavaMail 2, JavaBeans Activation Framework installation is simple, just extract the downloaded files, and add the included JAR file to the classpath of your machine. Here is the ClassPath on the author machine:
; C: /apps/java/javamail-1.2/mail.jar; c: /apps/java/javamail-1.2/mailpi.jar; c: /apps/java/javamail-1.2/pop3.jar; C: / apps / Java/javamail-1.2/smtp.jar;c: /apps/java/jaf-1.0.1/activation.jar
The Mailapi.jar file contains the core API class, and the pop3.jar and the SMTP.jar file contain their respective Email protocol implementation. (In this article we don't use the imap.jar file). It can be considered that the implementation is similar to the JDBC (Java Database Connection) driver, but it is used for message systems instead of for databases. As for the mail.jar file, it contains every JAR file above, so you can include only mail.jar and activation.jar files in your ClassPath. The Activation.jar file allows you to handle access to MIME types through the form of binary data streams. This section "can send a normal text" later will tell the DataHandler class, you can find relevant information there. As for the record, the remainder of this article does not have a comprehensive explanation to the API; but you can learn to do it. If you want more to learn about API information, you can see the PDF files in each download package and Javadoc. Once you have already installed this software, you need to know your email account to run the following example. You need to know your ISP's SMTP server name and POP server name, your email account login name, and your mailbox password. Figure 1 shows the details of the author used in Microsoft Outlook: (Figure) Sending an email through the SMTP to tell you how to send a basic Email message via SMTP. In the following, you will find the SimpleseEnder class, which reads your message from the command line, and then calls a separate method Send (...) to send them:
Package com.lotontech.mail; import javax.mail. *; import javax.mail.internet. *; import java.util. *; / *** a simple emil sender class. * / public class simplesender {/ ** * Main method to send a message given on the command line. * / Public static void main (string args []) {Try {string smtpserver = args [0]; string to = args [1]; string from = args [2] String subject = args [3]; string body = args [4]; send (SMTPServer, To, from, Subject, Body);} catch (exception ex) {system.out.println ("Usage: java com.lotontech .mail.simplesender " " smtpserver toaddress fromaddress subjecttext bodytext ");} system.exit (0);}
Next, running Simplesender as shown below, replace SMTP.MYISP.NET in your email settings with your own SMTP:
Java com.lotontech.mail.simplesender smtp.myisp.net bill@lotontech.com Ben@lotontech.com "Hello" "Just to Say Hello."
If it works normally, you will see the content shown in Figure 2 in the receiving end.
Figure 2 The message SIMPLesender class read from the Simplesender is mainly completed by the Send (...) method. The code is as follows:
/ *** "Send" method to send the message. * / public static void send to, string from, string subject, string body) {type {printerties version = system.getproperties (); // - - attaching to default session, or we could Start a new one - props.put ("mail.smtp.host", smtpserver; session session = session.getDefaultInstance (props, null); // - create a new Message - Message msg = new mimeMessage (session); // - set the from and to fields - msg.setfrom (new internetdress (from)); msg.seTrecipients (Message.RecipientType.to, Internetdress.Parse (To, FALSE)); // - We Could Include CC Recipients TOO - // IF (cc! = null) // msg.seTrecipients (Message.RecipientType.cc //, internetdress.parse (cc, false); / / - SET the SUBJECT AND BODY TEXT - MSG.SETSUBJECT (SUBJECT); msg.settext (body); // - set some other header information - msg.setheader ("x-mailer", "lotontechemail") Msg.setSentDate (new date ()); // - send the message - Transport.send (MSG); System.out.Println ("Message Sent OK.");} Catch (exception ex) {ex.printstacktrace ();}}}
First of all, please note that you get an emailsession (java.mail.session), no, you can't do anything. In this case, you call SESION.GETDEFULTINSTANCE (...) to get a shared session, and other desktop applications can also use it; you can also create a new session through the session.getInstance (...) method, which is for you The app is unique. We can then prove that the Email client application is the same for each user, such as it can be a Web-based Email system implemented with a servlet.
Creating a session requires some properties; if you send a message via SMTP, then at least set the mail.smtp.host property. In the API document you can find other properties.
Now you have a session and create a message. In this example, you can set the email address information, theme, and text, all of which are taken from the command line. You can also set some headers, including the date, etc., and you can also specify the recipient of replication (CC). Finally, you send messages through the Javax.mail.Transport class. If you want to know our EmailSession, please see the message constructor behind.
Not only you can send a setText (...) method in the normal text javax.mail.MAESSAGE class to assign the message content to the provided string, set the MIME to Text / Plain.
However, you can not only send ordinary text, you can also send other types of content through the setDateHandler (...) method. In most cases, you can specify file attachments by using "Other Types of Content", such as Word documents, but interesting is that you check the code here to find it to send a Java serialized object:
ByteArrayOutputStream byteStream = new ByteArrayOutputStream (); ObjectOutputStream objectStream = new ObjectOutputStream (byteStream); objectStream.writeObject (theObject); msg.setDataHandler (new DataHandler (new ByteArrayDataSource (byteStream.toByteArray (), "lotontech / javaobject")));
In the Javax.mail. * Package structure you may not find the DataHandler class because it belongs to the JavaX.Activation package of JavaBeans Activation Framework (JAF). Jaf provides a mechanism for processing data content types, which is mainly for Internet content, namely MIME types.
If you have tried the above code, send a Java object by email, you might touch the problem of positioning the ByteArrayDataSource class, because or mail.jar either Activation.jar is not included in the program. You can find it in the JavaMail Demo directory.
As for an attachment that you are interested in, you can create a Javax.ActiVation.FileDataSource instance in the DataHandler constructor. Of course, you can't send a file separately; it can be sent as an attachment to a text message. Maybe you need to understand the concept of multi-part messages, now I introduce you to this concept in the environment where I receive the email.
Accept Email in front of POP3, I introduced the javax.mail.part interface implemented by Javax.mail.Message. I will now explain its message part, it is important in this example. Let's take a look at Figure 3 first.
Figure 3 UML diagram of mail.part interface
Figure 3 shows a Message established in the previous example, which can be a message or a message part because it implements a Part interface. For any part, you can get its content (any Java object), and if you send a simple text message, the content object may be a string. For multi-segment messages, the content may be type Multipart, where we can get a separate body section, it itself implements a Part interface
In fact, when you have seen the code of the SimpleReceiver class, you will find that everything becomes clear. We use three parts to introduce the SimpleReceiver class: the first part, the definition of the class, and the main () method of obtaining connection details information from the command line; the second part, capture and view the Receive () method of the message coming in, the third part, print The printMessage () method for header information and each message content. Here are the first part:
Package com.lotontech.mail; import javax.mail. *; import javax.mail.internet. *; import java.util. *; import java.io. *; / *** a Simple email receiver class. * / public class SimpleReceiver {/ ** * main method to receive messages from the mail server specified * as command line arguments * / public static void main (String args []) {try {String popServer = args [0];. String popUser = args [1]; String popPassword = args [2]; receive (popServer, popUser, popPassword);} catch (Exception ex) {System.out.println ( "Usage: java com.lotontech.mail.SimpleReceiver" "popServer popUser Poppassword ");} system.exit (0);
Now let's use the command line to run it (remember to use your email settings to replace the command line parameters):
Java com.lotontech.mail.simplereceiver pop.myisp.net myusername mypasswordRecEceptRecEVE () method is called from the Main () method, which opens your POP3 mailbox check message in turn, and call printMessage () each time. code show as below:
/ *** "receive" method to fetch messages and them process * / public static void receive (String popServer, String popUser, String popPassword) {Store store = null; Folder folder = null; try {// - Get hold. of the default session - Properties props = System.getProperties (); Session session = Session.getDefaultInstance (props, null); // - Get hold of a POP3 message store, and connect to it - store = session.getStore ("POP3"); Store.Connect (POPSERVER, POPUSER, POPASSWORD); //Try to get Hold of the default folder - folder = store.getDefaultFolder (); if (folder == null) throw new exception "No Default Folder"; // - ... and its inbox - folder = folder.getFolder ("inbox"); if (folder == null) Throw new Exception ("no pop3 inbox"); //// - Open the folder forread only - folder.open (Folder.Read_only); // - Get the message [] msgs = folder.getMess (); for (int msgnum = 0; Msgnum Printing messages in this section, it is necessary to discuss the Javax.mail.Part interface mentioned earlier. The following code allows you to understand how to convert messages into its part interface and assign it to your MessagePart variable. For only part of the news, you need to print some information now. If you call MessagePart.getContent () to generate a multipart instance, you know that you are handling a multi-section message; in this case, you are getting the first multi-part message through getBodypart (0) and print it. Of course, you must also know if you have got this message itself, or just the first part of the message body. Only when the content is normal text or HTML, you can print this message, which is done by an inputStream. / *** "PrintMessage ()" Method To Print A Message. * / public static void printmessage (message message) {Try {// get the header information string from = ((internetdress) message.getFrom () [0]) .getPersonal (); if (from == null) from = (InternetDress) message.getFrom () [0]) .Getaddress (); system.out.println ("from:" from); string subject = message .getsubject (); system.out.println ("Subject:" Subject); // - Get the Message Part (IE The MessageTself) - Part MessagePart = Message; Object Content = MessagePart.getContent (); / / - or its first body part if it is a multipart message - IF (Content InstanceOf Multipart) {MessagePart = ((Multipart) Content) .GetBodypart (0); System.out.Println ("[Multipart Message]") } // - get the content type - string contenttype = messagepart.getContentType (); // - if The content is plain text, we can print it - system.out.println ("Content:" ContentType ); If (contenttype.startswith ("text / plain") || ContentType.StartSwith ("Text / H tml ")) {InputStream is = messagePart.getInputStream (); BufferedReader reader = new BufferedReader (new InputStreamReader (is)); String thisLine = reader.readLine ();! while (thisLine = null) {System.out.println ( Thisline = Reader.readLine ();}} system.out.println ("------------------------------------------------------------------------------------------------------------------ );} Catch (exception ex) {ex.printStackTrace ();}}} For the sake of simplicity, I assume that the first part of the message itself or the message body is printed. For real applications, you may want to check every part of the message body sequently, and take the corresponding action - print or save to disk, depending on the type of content. When you get every message from the message store, you have actually got a lightweight package. The acquisition of the data content is taken once every application - this is useful for you only want to download the message. SimpleReceiver test Let us do a test for SimpleReceiver. In order to let it have something to receive, I send the message shown in Figure 4 (Note: Message consists of text and an attachment) Figure 4 Test message for SIMPLERECEIVER Once the message is received, the message is considered to be a multi-part message. The text of the print is as follows: From: tony lotonsubject: Number 1 [Multipart Message] Content: Text / Plain; Charset = "ISO-8859-1" Attachment 1From Tony Loton. ------------------- ------------ Send your message out For interesting, and explain a novel usage of JavaMail API, I now briefly introduce my conversation Email project. You need to get a Lotontalk.jar file before doing this test, and add it to your classpath, add the method as follows: Set classpath =% classpath%; Lotontalk.jar You also need to modify code modifications in two places in the SimpleReceiver class. First, in the receive () method, put the following code: // - Get the message wrappers and process theme --MESSAGE [] msgs = folder.getMess (); for (int msgnum = 0; msgnum Replace with: // - get the message wrappers and process theme --Message [] msgs = folder.getMessages (); for (int msgnum = 0; msgnum Now add the following new method SpeakMessage (), which is similar to the initial printMessage () method. . / *** "speakMessage", a talking version of printMessage () * / public static void speakMessage (Message message) {String speech = ""; try {com.lotontech.talk.LOTONtalk speaker = new com.lotontech.talk .Lotontalk (); string from = ((InternetAddress) message.getFrom () [0]). GetPersonal (); if (from == null) from = (Internetdress) message.getFrom () [0]). GetAddress (); Speech = speech "from" from ","; string subject = message.getsubject (); speech = speech "SPEECT" SUBJECT ","; // - Get The Message Part (IE, The Message Itself ) - Part messagePart = message; Object content = messagePart.getContent (); // - ... or its first body part if it is a multipart message - if (content instanceof multipart) messagePart = ((multipart) content ) .getBodyPart (0); String contentType = messagePart.getContentType (); if (contentType.startsWith ( "text / plain") || contentType.startsWith ( "text / html")) {InputStream is = messagePart.getInputStream () ; BufferedReader Reader = New BufferedReader (New InputStrea) MREADER (IS)); string thisline = reader.readline (); while (thisline! = null) {Speech = Speech thisline "; thisline = reader.readLine ();} // - speak - speaker. Speech (Speech, True);}} catch (exception ex) {ex.printstacktrace ();}} Before you talk, you are accumulating the entire message into a string, so this program may only be a small message. As a choice, you can read a row and then speak one by one. Of course, I can't show the results to you, so you have to come to do experiments. You can also do some small trials, of course, not in this trial, some interesting features of speech synthesis: How to deal with numbers, and how to put all the words to imagine only the abbreviation of the first letter, then one I spel them out of one letter. in conclusion We have explained all the basic structural blocks of the application of the application that send and receive the email message, which involves the approach to sending and receiving Email. If you are the first time you have exposed JavaMail, is it discovered that email is not a difficult thing in your application. Source: http://www.yesky.com/20020713/1620276.shtml