The JavaMail API is an optional that can be used to read, write, and send electronic messages (standard extensions). You can use this package to create a Mail User Agent (MUA) program, which is similar to Eudora, Pine, and Microsoft Outlook these mail programs. Its main purpose is not to transmit, send, and forward messages as programs that send mail or other mail transport agents (MTA) types. In other words, users can interact with the MUA type program to read and write emails. MUA relies on MTA processing actual send tasks. The JavaMail API is designed to provide access to the agreement with the agreement. The way is to divide the API into two parts: • The first part of the API is the focus of this course. Basically, how to send and receive messages independent of the provider / protocol. • The second part uses specific protocol languages such as SMTP, POP, IMAP, and NNTP. If you want the JavaMail API to communicate with the server, you need to provide protocols for it. Since Sun has a sufficient introduction to a specific protocol provider, users can get free of charge, so this course does not introduce the contents of creating a specific protocol provider. Review Related Agreements Before learning the deep knowledge of the Javamail API, let's take a look at the protocol used in the API, in essence, there is a commonly used agreement: · SMTP · POP · IMAP · MIME you still need to understand NNTP and other protocols. It is understood that the basic principles of these agreements help you understand how to use the JavaMail API. The design of the API is not related to the agreement, so it cannot overcome the limitations of these basic protocols. If the selected protocol does not support some feature, the JavaMail API cannot add this feature. (As you will see later, this problem often encounters this problem when you operate the POP protocol). The SMTP Simple Mail Transfer Protocol (SMTP) is a mechanism for transmitting an email. In a JavaMail API environment, your JavaMail-based program will communicate with your company or Internet Service Provider (ISP) SMTP server. The SMTP server will forward the message to the SMTP server used as the received message, and finally the user can obtain the message via the POP or IMAP protocol. Due to support authentication, it is not necessary to SMTP server is an open repeater, but you need to make sure the SMTP server configuration is correct. There is no integration in the JavaMail API to handle functions such as configuring servers to forward messages or add / delete email accounts. The meaning of POPPOP is a post office protocol. The current version is 3, also known as POP3, which is defined in RFC 1939. POP is the mechanism for most people on the Internet to receive mail. It is supported for each mailbox of each user. This is all the work it does and is the root of most issues. When using the POP protocol, many of the features are familiar with, if you see how much new mail messages are received, POP does not support. These features are built into a mail program such as EUDORA or Microsoft Outlook, which can remember the last email received and how many new messages are calculated. Therefore, when using the JavaMail API, if you want to get such information, you will need to calculate yourself. IMAPIMAP is a more advanced protocol for receiving messages, which is defined in RFC 2060. The meaning of IMAP is "Internet Message Access Protocol", and the current version is 4th edition, also known as IMAP4. When using IMAP, your mail server must support this protocol.
You can't just simply transform the program to support IMAP, rather than supporting POP, counting everything in IMAP. Assuming your mail server supports IMAP, JavaMail-based programs can be used to have multiple folders on the server, and these folders can be shared by multiple users. Since the IMAP protocol has a more advanced feature, you may think that IMAP should be used by everyone, but the fact is not the case. Because IMAP will increase the load of the mail server, it requires the server to receive new messages, send messages to the requested user, and maintain these messages for each user in multiple folders. And this is a concentrated backup, so it will become bigger and bigger for a long time, and when the disk space is light, everyone will suffer. When using the POP protocol, the saved message can release the weight of the server. The meaning of Mimemime is "Multi-purpose Internet Snap Prosperity Agreement". It is not a mail transfer protocol. Instead, it defines the content of the transfer: the format, attachment, etc. of the message. Many documents define MIME protocols, including: RFC 822, RFC 2045, RFC 2046, and RFC 2047. As a JavaMail API, you don't need to worry about these formats. However, these formats do exist and use it for your program. NNP and other protocols Since the JavaMail API separates providers and other parts, you can easily add support for additional protocols. Sun offers a list of third-party providers that use Sun's unsupported protocols that are not supported by SUN. In this list, you will see a third party provider for NNTP (Network News Transfer Protocol) [News Group], S / MIME (Safety Multi-Purpose Internet Soup Extension) and other protocols. There are currently two versions of JavaMail APIs currently available: 1.2 and 1.1.3. All examples in this course apply to these two versions. The JavaMail API 1.2 is the latest, and JavaMail API 1.1.3 includes version 1.2.1 of the Java 2 Enterprise (J2EE) platform, so it is still very common. The version using the JavaMail API will have some impact on your download and installation. Both of these two versions work with JDK 1.1.6, Java 2 Standard (J2SE) platform 1.2.x and 1.3.x. Note: After the SUN's JavaMail tool is installed, many sample programs are seen in the demo directory. Installing JavaMail 1.2 To use the JavaMail 1.2 API, you can download the JavaMail 1.2 tool, then decompress the javamail-1_2.zip file and add the mail.jar file to a typical installation path. JavaMail 1.2 Tools with SMTP, IMAP4, and POP3 providers and core classes. After installing JavaMail 1.2, install the JavaBeans Activation Framework. Install JavaMail 1.1.3 To use JavaMail 1.1.3 API, you can download the JavaMail 1.1.3 tool, then decompress the javamail1_1_3.zip file and add the mail.jar file to the typical installation path. JavaMail 1.1.3 Tools with SMTP and IMAP4 providers and core classes. If you want to access the POP server with JavaMail 1.1.3, you need to download and install the POP3 Provider. Sun has a provider with a JavaMail tool. After downloading and unzipping the POP31_1_1.zip file, you also need to add POP3.jar to a typical installation path. After installing JavaMail 1.1.3, install the JavaBeans Activation Framework.
All versions of the JavaBeans Activation FrameworkJavaMail API require a JavaBeans Activation Framework (JavaBeans Activate Framework), which provides support for inputting any data block and can be processed accordingly. It seems that it seems that it is not very good, but the framework is the basic MIME type support that can be found in today's many browsers and mail tools. After downloading the frame, unzip the JAF1_0_1.zip file and add the activation.jar file to a typical installation path. For JavaMail 1.2 users, you should now add a mail.jar and activation.jar files to a typical installation path. For JavaMail 1.1.3 users, you should now add mail.jar, pop3.jar, and Activation.jar to a typical installation path. If you don't plan to use POP3, you don't need to add a pop3.jar file to a typical installation path. If you don't want to change the installation path environment variable, you can copy the JAR file to the lib / ext directory under the Java runtime environment (JRE) directory. For example, for the J2SE version 1.3, the default directory on the Windows platform should be c: /jdk1.3/jre/lib/ext. Using Java 2 Enterprise Edition If you are using J2EE, you don't need to do a special job when you use the basic JavaMail API; JavaMail API has a J2EE class. Just make sure the J2EE.jar file is located under the typical installation path and completes all settings. For J2EE 1.2.1, the POP3 provider is separately provided, so you need to download the provider and press the step of installing JavaMail 1.1.3, including the POP3 provider in J2EE 1.2.1. Users of J2EE 1.3 will get J2EE and POP3 providers, so you don't need to perform separate installations for POP3 providers. With these two versions of J2EE users do not need to install JavaBeans Activation Framework. Practice Set your JavaMail environment. Review core classes Before starting to study the Javamail class, first let users browse the core class that make up the API: session, message, address, verification program, transmission, storage, and folder. All of these classes can be found in the JavaMail API Javax.mail's top package, although you will frequently find that the subclasses you use yourself are found in the Javax.mail.Internet package. The Session class session class defines a basic mail session. Other work can be successfully implemented by this session. The session object uses the java.util.properties object to get information such as mail servers, username, passwords, and other information that can be shared throughout the application. The SESSION class constructor is private. You can get a single default session that can be shared by getDefaultInstance () method: Properties PROPS = New Properties (); // Fill Props with any informationationSession session = session.getDefaultInstance (props, null); or you can use GetInstance Methods Create a unique session: Properties Props = New Properties (); // Fill Props with any informationationSession session = session.getInstance (props, null); NULL parameters under these two situations are an Authenticator object, it Not used at this time.
For more information, please refer to the following "Autherticator" section. In most cases, use the shared session is enough, even if you process the mail session for multiple user mailboxes. You can add a combination of your username and password behind the communication process, and keep all everything is independent. Once you have created your own session object once you create your own session object, it's time to create the message you want to send. This is the type of message to use. As an abstract class, you must operate a subclass, in most cases, the subclass is javax.mail.internet.mimeMeMessage. A MIMEMESSAGE is a message that understands the MIME type and header (in different RFC documents). The header of the message is strictly limited to only the US-ASCII character, although non-ASCII characters can be encoded into certain header fields. You can create a message by passing the Session object to the MIMEMessage constructor: MIMEMESSAGE MESSAGE = New MimeMeMessage (SESSION); Note: There are other constructors, such as constructive of input streams originated from RFC822 formatted by the message. . Once a message is created, you can set each of its parts, such as the message implementation Part (section) interface (MIMEMESSAGE). The basic mechanism of setting content is a setContent () method, which has parameters indicating content and mime types: Message.SetContent ("Hello", "Text / Plain"); however, if you are using MimeMessage, and your message is pure Text, then you can use the setText () method. This method only needs a parameter representing the actual content, the default MIME type is plain text: message.setText ("Hello"); for plain text messages, the setText () method is more often used to set the content. To send other types of messages, such as HTML messages, use the setContent method (). More use of HTML messages now. To set the topic, you can use the setSubject () method: message.setSubject ("first"); the Address class is created once a session and message is created, and you need to use the Address class to be addressed with the Address class. Like the Message class, the Address class is also an abstract class. You can use the Javax.mail.Internet.InternetAddress class. To create an address with an email address, you can pass the email address to the Address class constructor: address address = new internetdress ("president@whitehouse.gov"); if you want a name to appear after the email address You can also pass it to the constructor: address address = new internetdress ("President@whitehouse.gov", "George Bush"); create an address for the message of the message and the To (Receiver) field Object. The sender of the message is indicated in the sended message unless your mail server blocks this. Once the address is created, there are two ways to let you connect the address to the message. To identify the sender, you can use setFrom () and setReplyto () methods.
Message.SetFrom (Address) If your message needs to display multiple addresses, you can use the addFrom () method: address address [] = ...; message.addfrom (address); for authentication message recipients, you can use ADDRECIPIENT () method. In addition to the need for an address parameter, this method also needs a message.recipientType property (the reception type of the message). The three predefined types of the Message.AddRecipient address are as follows: • Message.RecipientType.cc · message.recipientType.cc · message.recipientType.bcc therefore, if a message will be sent to the vice president, will also send The copy of the message gives the first lady, using the following code: address toaddress = new internetdress ("vice.president@whitehouse.gov"); address ccaddress = new internetdress ("first.lady@whitehouse.gov"); message .addrecipient (Message.RecipientType.to, toaddress); message.addrecipient (message.recipienttype.cc, ccaddress); JavaMail API does not provide a mechanism for checking email address validity. You can write a program that supports scan valid characters (in RFC 822 documents) or check MX (Mail Switch) records, which exceeds the range of JavaMail APIs. The Authenticator class is the same as the Java.Net class, and the JavaMail API can use the Authenticator class to access protected resources through the username and password class. For JavaMail API, this protected resource refers to a mail server. JavaMail's Authenticator class can be found in the javax.mail package and is different from the Java.Net class that is the same name. JavaMail and Java.net do not share the same Authenticator class name when JavaMail API works under Java 1.1, because Java 1.NET is not included in Java 1.1. To use the Authenticator class, you can use the subclass of the abstract class and return a passwordAuthentication instance through the getPasswordAuthentication () method. When you create, you must record the Authentication class with a session. Since then, you will notify you of Authenticator when you need authentication. A window will pop up, or read the username and password from a profile (although not encrypted is not secure), and return them to the call as a passwordAuthentication object. Properties props = new Properties (); // fill props with any informationAuthenticator auth = new MyAuthenticator (); Session session = Session.getDefaultInstance (props, auth); Transport class last step is to send the message using Transport class. This class sends a message using a language specific to protocol (usually SMTP).
It is an abstraction class that is similar to the Session class. You can use the default version of this class with only the static send () method: Transport.send (Message); or you can get a specific instance from the session for your protocol, then pass your username and password (You can be empty when you can send a message, and finally close the connection: message.savechanges (); // impordit with send () Transport transport = session.getTransport ("smtp"); transport.connect (Host, Username, Password Transport.sendMessage (Message, Message.GetallRecipients ()); transport.close (); When you need to send multiple messages, it is recommended to adopt the latter method because it will keep the message between the message -ams active servers. The basic Send () mechanism creates a separate connection for each method. Note: To see the mail server mail command, you can use the session.setdebug (true) method to set the debug logo. The Store and the Folder class use the Session class to get the message, and the message is similar to the send message. However, after getting the session, it is likely to use the username and password or the Authenticator class to connect the Store class. Like the Transport class, you have to tell the Store class what protocol is used: // store store = session.getStore ("IMAP"); store store = session.getStore ("POP3"); Store.Connect (Host, Username, Password ); After connecting the Store class, you can get a Folder class. You must open the class before reading the message. Folder folder = store.getFolder ("Inbox"); folder.Open (Folder.Read_only); message message [] = folder.getMess (); For POP3 protocol, the only available folder is Inbox. If you are using an IMAP protocol, you can use other folders. Note: Sun's provider is originally advisable. Message message [] = folder.getMess (); this statement is a slow operation of reading the message from the server, so it is only when you really need to get the message section (the content is the content of the message) Use this statement. Once the message is read, you can use the getContent () method to get its content, or write its content into a stream using the Writeto () method. The getContent () method only gains the message content, and the Writeto () method will also output a header. System.out.println ((MIMEMESSAGE) message. GetContent ()); Once you have read the mail, you can close the folder and the storage connection. Folder.close (ABOOLEAN); Store.Close (); Boolean variables passing to the folder's close () method specify whether the folder is updated by clearing the deleted message. Continue to advance, understanding the use of these seven classes, is the full content required to use the JavaMail API to handle almost everything. The JavaMail API constructed in these seven classes, most of which is to perform tasks in almost identical or specific ways, as if the content is an attachment. Specific tasks, such as: search, isolation, etc. will be described later.
You have seen how to operate the core part of the JavaMail API using JavaMail API. In the following sections, you will learn how to connect several parts to perform specific tasks. Send messages Send email messages involve gain sessions, create, and populate messages and send messages. You can specify your SMTP server by setting the mail.smtp.host property for the Properties object to be passed. String host = ...; string to = ...; // get system.getiesproperties version = system.getProperties (); // setup mail serverprops.put ("mail.smtp.host", host); // Get sessionSession session = Session.getDefaultInstance (props, null); // Define messageMimeMessage message = new MimeMessage (session); message.setFrom (new InternetAddress (from)); message.addRecipient (Message.RecipientType.TO New InternetAddress (to)); Message.SetSubject ("Hello Javamail"); Message.Settext ("Welcome To Javamail"); // Send MessageTransport.send (Message); You should write code in the TRY-CATCH block, An exception can throw an exception when creating a message and send it. Exercise Send your first message Get Message For reading mail, first you have to get a session, then get and connect to a corresponding storage of your inbox, then open the corresponding folder, and then Get the message. At the same time, don't forget the connection after the operation is complete. String host = ...; string username = ...; string password = ...; // Create Empty PropertiesProperties PROPS = New Properties (); // Get sessionSession session = session.getDefaultInstance (props, null); // Get the storestore store = session.getStore ("POP3"); Store.Connect (Host, Username, Password); // Get FolderFolder Folder = Store.GetFolder ("Inbox"); Folder.Open (Folder.Read_only); / / Get directoryMessage Message [] = folder.getMess (); for (int i = 0, n = message.length; i As a result, the sender address list can be empty, and the getFrom () [0] call will throw an exception. To display the entire message, you can prompt the user after the sender and the subject field of the message, if you want to see the content of the message, you can call the Writeto () method of the message. BufferedReader reader = new BufferedReader (new InputStreamReader (System.in)); // Get directoryMessage message [] = folder.getMessages (); for (int i = 0, n = message.length; i You can configure Properties with hosts, and tell Session about your customary Authenticator instance, as follows: // setup profroperties (); prOPs.put ( "mail.pop3.host", host); // Setup authentication, get sessionAuthenticator auth = new PopupAuthenticator (); Session session = Session.getDefaultInstance (props, auth); // Get the storeStore store = session.getStore ( " POP3 "); store.connect (); then you can use the subclass of the Authenticator class and return a PasswordAuthentication object through the getPasswordAuthentication () method. Below is an example of such an implementation, one of which is available for both part of the content. It is not a Project Swing Guide, just entering two parts in a field, they are separated by commas. import javax.mail *;. import javax.swing *;. import java.util *;. public class PopupAuthenticator extends Authenticator {public PasswordAuthentication getPasswordAuthentication () {String username, password; String result = JOptionPane.showInputDialog ( "Enter 'username, password ' "); StringTokenizer st = new StringTokenizer (result,", "); username = st.nextToken (); password = st.nextToken (); return new PasswordAuthentication (username, password);}} because PopupAuthenticator dependent on Swing Therefore, event processing threads for AWT will be initiated. This is essentially as you add a call to system.exit () in your code to terminate the execution of the program. Reply Message The Message class contains a reply () method to configure a new message with the correct recipor and topic (add "RE::", if not). This method does not add anything to the message, just copy the sender or reply to the header for the new recipient. This method uses a Boolean parameter that prompts whether only reply to the sender (false) or reply to the owner (TRUE). MimeMessage reply = (mimeMessage) message.reply (false); reply.setdress ("president@whitehouse.gov"); reply.setText ("Thanks"); transport.send (reply); when sending a message To configure a reply to the address, you can use the setLyto () method. Exercise Reply Message Forward Message Forward Messages Take a little more, there is no way to forward messages, you can create messages to be forwarded by handling each part of the message. An email message can be composed of multiple parts, each part is a Bodypart, or a more special, MIMEBODYPART when operating the MIME message. Different packets are combined into a container called Multipart, or more special, is a MIMEMULTIPART container. To forward a message, you have to create a part of the part of the message text, and the second part for the message to be forwarded, and combine the two parts into a Multipart (multiple parts). Then you can add this Multipart to a suitable indicated address of the address and send it. This is the essence of forwarding messages. To copy the contents of a message to another, just copy it through its DataHandler class, it is a class from JavaBeans Activation Framework. // Create the message to forwardMessage forward = new MimeMessage (session); // Fill in headerforward.setSubject ( "Fwd:" message.getSubject ()); forward.setFrom (new InternetAddress (from)); forward.addRecipient ( Message.RecipientType.TO, new InternetAddress (to)); // Create your new message partBodyPart messageBodyPart = new MimeBodyPart (); messageBodyPart.setText ( "Here you go with the original message: / n / n"); // Create a multipart to combine the partsMultipart multipart = new MimeMultipart (); multipart.addBodyPart (messageBodyPart); // Create and fill part for the forwarded contentmessageBodyPart = new MimeBodyPart (); messageBodyPart.setDataHandler (message.getDataHandler ()); / / Add part to multi partmultipart.addBodyPart (messageBodyPart); // associate multipart with messageforward.setContent (multipart); // Send messageTransport.send (forward); operational resources accessory attachment is associated with a mail message, usually kept in Outside the message, such as: a text file, spreadsheet or picture. For common mail programs like Eudora and Pine, you can attach resources to your message via JavaMail API and get attachments when you receive messages. Send attachments The accessories are very similar to forward messages, and you want to create all parts that make up the full message. After creating a message text, you add a DataHandler class processing, which is your attachment, not a shared handler in the forward message. When you read attachments from a file, the data resources of the attachment are FileDataSource; when reading from the URL, it is URLDataSource. Once you have your own DataSource, you can only pass it to the DataHandler class before you finally be attached to the Bodypart, you can pass it. Assuming that you want to keep the original file name of the attachment, the last thing you want to do is to set the file name associated with the attachment with the setFileName () method of the Bodypart class. All these operations are as follows: // Define messageMessage message = new MimeMessage (session); message.setFrom (new InternetAddress (from)); message.addRecipient (Message.RecipientType.TO, new InternetAddress (to)); message.setSubject ( "Hello JavaMail Attachment"); // Create the message part BodyPart messageBodyPart = new MimeBodyPart (); // Fill the messagemessageBodyPart.setText ( "Pardon Ideas"); multipart multipart = new MimeMultipart (); multipart.addBodyPart (messageBodyPart) ; // Part two is attachmentmessageBodyPart = new MimeBodyPart (); DataSource source = new FileDataSource (filename); messageBodyPart.setDataHandler (new DataHandler (source)); messageBodyPart.setFileName (filename); multipart.addBodyPart (messageBodyPart); // Put Parts in messageMessage.setContent (MULTIPAR); // send the message; when you include an attachment, if your program is a servlet, your user must upload an attachment and tell you to send a message Where is the location. Each file uploaded can be processed with a form that is encoded in Multipart / form data (FORM-DATA). Simply get the original file name by getFileName () method, and get the input stream via the getInputStream () method. Multipart MP = (Multipart) Message.getContent (); for (int i = 0, n = multipart.getcount (); i IF (Message.GetContentType (). Equals ("text / html")) {string content = (String) message.getContent (); jframe frame = new jframe (); JeditorPane text = new JeditorPane ("text / html", content); text.setEditable (false); JScrollPane pane = new JScrollPane (text);. frame.getContentPane () add (pane); frame.setSize (300, 300); frame.setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE); frame. SHOW ();} In the message, it contains images, if your HTML message is embedded as a picture of a message, and you want to keep the message content, you must regard the picture as an attachment and use special communication. The symbol URL references the image, which references the content ID message of the picture attachment. The processing of embedded images is very similar to additional files to the message, the only difference is that you must distinguish between MIMEMULTIPART, which part is related to the constructor (or via the setSubType () method) And set the content ID header of the picture to any string, which will be used as the source path of the image in the IMG tag. The following shows a complete example: String file = ...; // Create the messageMessage message = new MimeMessage (session); // Fill its headersmessage.setSubject ( "Embedded Image"); message.setFrom (new InternetAddress (from )); message.addRecipient (Message.RecipientType.TO, new InternetAddress (to)); // Create your new message partBodyPart messageBodyPart = new MimeBodyPart (); String htmlText = " Hello H1>" "< img src = / "cid: memememe /"> "; messageBodyPart.setContent (htmlText," text / html "); // Create a related multipart to combine the partsMimeMultipart multipart = new MimeMultipart (" related "); multipart. addBodyPart (messageBodyPart); // Create part for the imagemessageBodyPart = new MimeBodyPart (); // Fetch the image and associate to partDataSource fds = new FileDataSource (file); messageBodyPart.setDataHandler (new DataHandler (fds)); messageBodyPart.setHeader ( "Content-id", "memememe"); // add part to multi-partmultipart.addbodypart (messagebodypart); // associate multi-part with messageMessage.setContent (Multipart); Exercise Send HTML with pictures Search for the Searchterm search JavaMail API contains a filtering mechanism that can be used to create SearchTerm, which can be found in the Javax.mail.Search package. Once you have created SearchTerm, you can ask a message to match the message and retrieve the array of message objects: searchterm st = ...; message [] msgs = folder.search (st); 22 different classes available Help create search criteria. · ANDTERM class) · OR condition (ORTERM class) · NotTerm class) · Sent DateTerm class) · Content Class (BodyTerm class) · HEADERM / RECIPIENTSTRINGTERM, SUBJECTTERM, Etc.) Essentially, you can create a logical expression for the matching message, then search. For example, the condition search example of a message is displayed below, which is provided with an ADV topic string, and its sender field is Friend@public.com.