JavaMail API Introduction

xiaoxiao2021-03-06  40

JavaMail API Introduction

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 protocol

Before learning the deep knowledge of the JavaMail API, let us take a look at the agreement used in the API, in essence, there is a common agreement:

· SMTP

· POP

· IMAP

· Mime

You also 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).

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.

POP

The meaning of POP 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.

IMAP

IMAP 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.

Mime

The meaning of MIME is "Multi-purpose Internet Mail Expansion 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 the provider 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.

installation

There are currently two versions of JavaMail APIs most commonly used: 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.

Install 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 the 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 the 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 a 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.

Install JavaBeans Activation Framework

All of the JavaMail APIs require JavaBeans Activation Framework (JavaBeans Activation 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.

Use 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.

Exercise

Set your JavaMail environment.

Review core

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.

Session class

The 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 Information

Session session = session.getDefaultInstance (Props, NULL);

Alternatively, you can create a unique session with the getInstance () method: Properties PROPS = New Properties ();

// Fill Props with Any Information

Session session = session.getInstance (Props, NULL);

NULL parameters in these two situations are an Authenticator object, which is 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.

Message class

Once you have created 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 MimeMessage (session);

Note: There are other constructors, such as a constructor for creating a message from the RFC822 formatted input stream.

Once a message is created, you can set each of its parts, such as the message implementation Part (section) interface (MIMEMESSAGE). The basic mechanism for setting content is a setContent () method, which has parameters representing content and MIME types:

Message.SetContent ("Hello", "Text / Plain");

However, if you are using MIMEMESSAGE, and your message is a plain text, 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");

Address class

Once a session and message is created, you need to fill the content for the message, you need to use the Address class to be your letter. 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 constructor of the Address class:

Address Address = New InternetAddress ("

PRESIDENT@whitehouse.gov ");

If you want a name to appear after an email address, you can also pass it to the constructor:

Address Address = New InternetAddress ("

President@whitehouse.gov "," George Bush "); create an address object for the FROM field and the To (Receiver) field. Unless your mail server blocks this, you want to send the message The sender of the message is promised.

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);

To authenticate the message recipient, you can use the 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).

Message.addrecipient (Type, Address)

The three predefined types of the address are as follows:

· Message.RecipientType.to

· Message.RecipientType.cc

· Message.RecipientType.bcc

Therefore, if a message will be sent to the vice president, the copy of the message will be sent to the first wife, then the following code:

Address toaddress = New InternetAddress ("

Vice.president@whitehouse.gov ");

Address ccaddress = new internetaddress ("

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.

Authenticator class

Like the Java.Net class, JavaMail API can use the Authenticator class to access protected resources through the username and password. 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 Information

Authenticator auth = new myauthenticator ();

Session session = session.getDefaultInstance (Props, Auth);

TRANSPORT class

The last step of sending messages is to use the 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 by calling a static Send () method:

TRANSPORT.SEND (MESSAGE);

Alternatively, you can get a specific instance from a session for your protocol, then pass your username and password (you can empty when you don't have to be empty) and send a message, and finally close the connection:

Message.savechanges (); // implicit 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 use the latter method because it will keep the connection 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.

Store and Folder class

Use the Session class to get the message, starting with the send message at the beginning. 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:

// store store = session.getStore ("IMAP");

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.getMessages ();

For the POP3 protocol, the only folder available 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 email, you can close the folder and the storage connection.

Folder.close (aboolean);

Store.Close ();

The Boolean variable of the Close () method passed to the folder specifies whether the folder is updated by clearing the deleted message.

Keep going

In fact, understanding the use of these seven classes is to use the JavaMail API to handle all the contents required for 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.

Use the JavaMail API

You have seen how to operate the core part of the JavaMail API. In the following sections, you will learn how to connect several parts to perform specific tasks.

send messages

Send email messages involve acquisition 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 from = ...;

String to = ...;

// Get System Properties

Properties PROPS = system.getproperties ();

// setup mail server

Props.PUT ("mail.smtp.host", host);

// Get session

Session session = session.getDefaultInstance (Props, NULL);

// define message

MimeMessage 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 Message

TRANSPORT.SEND (MESSAGE);

You should write code in the Try-Catch block to throw an exception when you create a message and send it.

Exercise

Send your first message

Get a message

For reading emails, first you have to get a session, then get and connect to a corresponding folder, then open the appropriate 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 PROPERTIES

Properties PROPS = New Properties ();

// Get session

Session session = session.getDefaultInstance (Props, NULL);

// Get The Store

Store = session.getStore ("POP3");

Store.Connect (Host, UserName, Password);

// Get Folder

Folder folder = store.getfolder ("inbox");

Folder.open (Folder.Read_only);

// Get Directory

Message message [] = folder.getMessages ();

For (int i = 0, n = message.length; i

System.out.println (i ":" Message [i] .GetFrom () [0]

"/ t" message [i] .Getsubject ());

}

// Close Connection

Folder.close (false);

Store.Close ();

What operations do every message must be decided. The above code block only shows the sender and the subject of the message. 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 Directory

Message message [] = folder.getMessages ();

For (int i = 0, n = message.length; i

System.out.println (i ":" Message [i] .GetFrom () [0]

"/ t" message [i] .Getsubject ());

System.out.println ("Do you want to read message?"

"[YES to read / quit to end]");

String line = reader.readline ();

IF ("Yes" .Equals (line)) {

Message [i] .writeto (system.out);

} else if ("quit" .Equals (line)) {

Break;

}

}

Exercise

checking emails

Delete messages and logos

Delete messages involve the symbol of the operation and message association. There are different signs for different states, some markers are defined by the system, and some are defined by the user. The predefined flag is defined in the internal class flags.flag, as shown below:

· Flags.flag.answered

· Flags.flag.deleted

· Flags.flag.draft

· Flags.flag.Flaged

· Flags.Flag.recent

· Flags.flag.seen

· Flags.Flag.user

Just because the logo exists, it does not mean that the logo is supported for all mail server / providers. For example, in addition to deleting messages, the POP protocol does not support them. Check that the new email is not a POP task, but it has been built into the mail client. To figure out what logo is supported, you can use the getPermanentFlags () method to query the folder. To delete a message, you need to set the delete flag for the message:

Message.Setflag (Flags.Flag.deleted, true);

The folder is opened in Read_WRITE (read-write) mode:

Folder.Open (Folder.Read_write);

Then, processes all the messages, turn off the folder and pass the TRUE value to wipe the deleted message.

Folder.close (True);

Users can use the Folder class's ExpUnge () method to delete the message. However, this method does not work on Sun's POP3 provider. Other providers may not implement their functions may not be implemented. It is more likely to apply to the IMAP provider. Since POP only supports simple access to the inbox, you will have to close the folder to delete messages when using Sun's provider.

To remove the logo, just pass a FALSE value to the setflag () method. To see if a flag is set, you can use the isset () to check.

Self-verification

Previously learned to use the Authenticator class to enter the username and password at needed, not in the form of a string. Here, you will really see how to use verification more fully.

You don't need to connect to the Store using the host, username, and password, you can configure Properties with hosts and tell Session about your customary Authenticator instance, as shown below:

// setup Properties

Properties PROPS = system.getproperties ();

Props.Put ("mail.pop3.host", host);

// setup authentication, get session

Authenticator auth = new popupauthenticator ();

Session session = session.getDefaultInstance (Props, Auth);

// Get The Store

Store = session.getStore ("POP3");

Store.Connect ();

Then you can use the subclass of the Authenticator class and return a passwordAuthentication object via 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 automator {

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);

}

}

Since PopupAuthenticator relies on Swing, event handling threads for AWT will be launched. 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 recipient 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.setFrom (New InternetAddress "

PRESIDENT@whitehouse.gov "));

Reply.setText ("Thanks");

TRANSPORT.SEND (Reply);

When sending a message, you can configure a reply to the address to use the setReplyto () method.

Exercise

Reply Mail

Forward message

The content involved in the forwarding message is slightly more, without a method specifically for forwarding messages, you can create messages to be forwarded by processing various parts that make up messages.

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 forward

Message forward = new mimeMessage (session);

// Fill in Header

Forward.setsubject ("fwd:" message.getsubject ());

Forward.SetFrom (New InternetDress (from));

Forward.Addrecipient (message.recipienttype.to,

NEW InternetAddress (to));

// Create your new message Part

Bodypart MessageBodypart = new mimebodypart ();

MessageBodypart.Settext

"Here You Go with The Original Message: / N / N");

// Create a multi-part to combine the partsmultipart multipart = new mimemultipart ();

Multipart.addbodypart (MessageBodypart);

// Create and Fill Part for the Forwarded Content

Messagebodypart = new mimebodypart ();

MessageBodypart.SetDataHandler ());

// add part to multi part

Multipart.addbodypart (MessageBodypart);

// Associate Multi-Part with Message

Forward.SetContent (Multipart);

// send Message

Transport.send (Forward);

Operating attachment

Attachment is the resource associated with message messages, usually saved outside of 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

Send attachments is very similar to forwarding messages, you have to create various 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 of these operations are as follows:

// define message

Message 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 message

MessageBodypart.Settext ("pardon ideas");

Multipart Multipart = new mimemultipart ();

Multipart.addbodypart (MessageBodypart);

// Part two is attachment

Messagebodypart = new mimebodypart ();

DataSource Source = New FileDataSource (filename);

MessageBodypart.SetDataHandler (new datahandler (source);

MessageBodypart.setFileName (filename);

Multipart.addbodypart (MessageBodypart); // Put Parts in Message

Message.setContent (Multipart);

// send the message

TRANSPORT.SEND (MESSAGE);

When you include an attachment in the message, if your program is a servlet, your user must upload an attachment and tell you where to send the message to where. Each file uploaded can be processed with a form that is encoded in Multipart / form data (FORM-DATA).

Method = post action = "/ myservlet">

Note: The size of the message is subject to your SMTP server, not by JavaMail API. If there is a problem, you can consider adding the spatial size of the Java stack area by setting the MS and MX parameters.

Exercise

send attachments

Get an attachment

Removing the attachment from the message is slightly more than the operation involved in the send attachment, and MIME does not have a simple attachment concept. When the message comes with an attachment, the content of the message is a Multipart object. Then you need to handle each part to get the main contents and accessories. The part of the part.attachment configuration is obviously an attachment by the part.getdisposition () method. At the same time, attachments can also be configured without configuration (and non-text MIME types) or part.inline configuration. When the configuration is part.attachment or part.inline, you can save it from the content of the message section. 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

Part part = Multipart.getBodypart (i));

String disposition = part.getdisposition ();

IF ((Disposition! = NULL) &&&

(Disposition.equals (part.attachment) ||

(Disposition.equals (part.inline))) {

Savefile (Part.getFileName (), Part.getInputStream ());

}

}

The SaveFile () method is only used to create a file according to the file name, read bytes from the input stream, and write them into a file. If the file already exists, add a number after the file name until a file that does not exist is found.

// from savefile ()

File File = New File (filename);

For (int i = 0; file.exists (); i ) {

File = new file (filename i);

}

The above code describes a simplest example of the respective part of the message being labeled. To contain all the cases, it is also necessary to process the Disposition Value as the NULL and the message section as the MIME type. IF (Disposition == NULL) {

// Check if plain

MimeBodypart MBP = (MIMEBODYPART) Part;

IF (MbP.ismType ("text / place") {

// Handle Plain

} else {

// Special Non-attachment Cases Here of Image / GIF, Text / HTML, ...

}

...

}

HTML message

Sending an HTML-based message is slightly complicated than sending a plain text message, although it doesn't need to do a lot of work. It all depends on your specific needs.

Send HTML message

If all the work you want to do is to send an equivalent HTML file as a message, let the mail reader worry about any embedded picture or related fragment, then you can use the setContent () method to pass in strings Message content and set the content type to Text / HTML.

String htmltext = "

Hello "

"

http://www.jguru.com/images/logo.gif/ ">";

Message.SetContent (HTMLText, "Text / HTML"));

At the receiving end, if you get the message with a JavaMail API, there is no built-in any function to display messages in an HTML format in this API. JavaMail API is only viewed in the form of a word stream. To display messages in an HTML format, you must use Swing JeditorPane or some of the third-party HTML reader components.

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 contains pictures

On the other hand, if your HTML message is embedded as a picture as a message, and you want to keep the message content, you must see the picture as an attachment and use the special communication identifier URL to reference the image, the communication identifier Quoted is 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 Message

Message message = new mimeMessage (session); // Fill ITS Headers

Message.SetSubject ("Embedded Image");

Message.SetFrom (New InternetAddress (from));

Message.addrecipient (message.recipienttype.to,

NEW InternetAddress (to));

// Create your new message Part

Bodypart MessageBodypart = new mimebodypart ();

String htmltext = "

Hello "

"";

MessageBodypart.SetContent (HTMLText, "Text / HTML");

// Create a related multi-part to combine the parts

MimeMultipart Multipart = New MimeMultipart ("Related");

Multipart.addbodypart (MessageBodypart);

// CREATE Part for the Image

Messagebodypart = new mimebodypart ();

// fetch the image and associate to pie

DataSource fds = new fileDataSource (file);

MessageBodypart.SetDataHandler (New DataHandler (FDS));

MessageBodypart.setHeader ("Content-ID", "MeMememe");

// add part to multi-part

Multipart.addbodypart (MessageBodypart);

// Associate Multi-Part with Message

Message.setContent (Multipart);

Exercise

Send HTML message with a picture

Search with Searchterm

The JavaMail API contains a filtering mechanism that can be used to create Searchterm (search criteria), which can be found in the Javax.mail.Search package. Once you have created Searchterm, you can ask a message to match a folder and retrieve the array of message objects:

Searchterm ST = ...

Message [] msgs = folder.search (st);

22 different classes can be used to help create search criteria.

· ANDTERMICE (ANDTERM class)

· OR condition (ORTERM class)

· NOT Class (NOTTERM class)

· SENT DATE condition (SentDateterm class)

· Content Condition (Bodyterm class)

· HEADER Condition (Recipientterm / RecipientStringterm, Subjectterm, ETC.)

In essence, 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 (partially brought) an ADV topic string, the sender field is

Friend@public.com. You may consider running the query periodically and automatically delete any returned messages. Searchterm ST =

New ORTERM

New SubjectTerm ("Adv:"),

New fromstringterm ("

Friend@public.com "));

Message [] msgs = folder.search (st);

转载请注明原文地址:https://www.9cbs.com/read-70489.html

New Post(0)