JavaMail Access Hotmail Mailbox _jsp programming

Source: Internet
Author: User
Tags imap
I believe many people have MSN Chat tool account number, such as abc@hotmail.com, this account is actually an e-mail address, you can perform normal mail transceiver function, you can through the Web site http://www.hotmail.com To access and manipulate this mailbox to send and receive mail. But this mailbox has a limit is that it does not provide POP3 or SMTP service, which means that the general mail client tools can not use this mailbox, although there are many mail tools to support Hotmail mailbox, But if we need to increase support for Hotmail mailboxes in our Java projects, it's often not known where to start, because the javamail provided by Sun does not in itself provide support for other protocols except Pop3/imap and SMTP.

But in fact, JavaMail only defines a set of platform-independent mail program frameworks, or interfaces, that exist as Java optional packages. So it can be said that JavaMail does not care about the protocols used, whether POP3, SMTP, IMAP and, of course, the HTTP protocol for Hotmail. For the JavaMail client is also the case, the following figure is a simple javamail structure map, through the transport to send mail, through the store to achieve the collection of messages, and the implementation of different protocols, JavaMail concept is called provider , you only need to implement your own provider based on the interface defined by JavaMail.


To enable access to Hotmail mailboxes via JavaMail, we need to bridge the JavaMail interface with the access interface provided by Hotmail services. Before that we must first understand the interface protocol used by Hotmail.

Hotmail provides a service based on HTTP protocol via address http://services.msn.com/svcs/hotmail/httpmail.asp, which is different from our browser access http://www.hotmail.com This address, the latter address is to provide users with a browser-based access interface to operate the mailbox, you can, of course, by writing HTTP client program to parse the page and get the message, but this is not only to achieve a very high degree of complexity, And every time the page style changes after the program has to do the corresponding adjustment, so does not have the universality, obviously is not feasible. The address http://services.msn.com/svcs/hotmail/httpmail.asp is different, and it provides a fixed application interface. When you use the browser to access the address, the following form will pop up:


And when the correct username and password will pop up again or twice the prompt window, but the message is different, the operation completed after the page can not be displayed error, the error code is 405 (resources are not allowed). Therefore, the service is not allowed to be accessed through the browser.

In fact, Hotmail uses WebDAV to provide an application programming interface based on the HTTP protocol, and WebDAV (Web Distributed Authoring and Versioning) has become an important web communication protocol. The problem that WebDAV has to solve is:

1. Overwrite protection: HTTP 1.1 cannot ensure that clients can protect resources and can make changes while other clients edit them at the same time. With WebDAV, you can lock resources in a variety of ways so that other clients know that you are interested in the resources being discussed, or prevent other clients from accessing the resource.

2. Resource management: HTTP can only access individual resources directly. WebDAV provides a way to organize your data more efficiently. WebDAV introduces the concept of a collection that can contain resources (similar to a file system folder). Resource management through WebDAV includes the ability to create, move, copy, and delete collections, as well as resources or files in the collection.

3. Document properties: Different types of data have unique properties that help describe the data. For example, in an e-mail message, these properties may be the sender's name and the time the message was received. In a collaboration document, these properties may be the name of the original author of the document and the name of the last editor. Because people use different types of documents, the list of possible property types becomes infinitely larger. XML is an extensible communication tool required for WebDAV.

For more information on WebDAV, see the resources at the end of this article.

The interface based on the specific protocol WebDAV makes the Hotmail mail client program more stable and reliable than the browser page that resolves Hotmail. In understanding the basic interface of the JavaMail API and the protocols provided by Hotmail, the topic of this article becomes very specific, that is, if you write a javamail based on WebDAV Provider (JavaMail Provider) and use this provider to implement Hotmail messaging, but the topic is too big and beyond the scope of an article, so we'll introduce an open source project Jdavmail, and details how to implement the Hotmail mail through this project to send and receive function.

Jdavmail is an open source JavaMail provider project that allows access to the WebDAV based mail service, like a Hotmail mailbox. You can download to the latest version of the program at the Http://sourceforge.net/projects/jdavmail website. Jdavmail uses the Commons httpclient on Jakarta to communicate with the server as an HTTP client component, using Jdom to parse XML data, and because HttpClient projects use Commons Logging to the output of the diary, so commons-logging is also necessary, these three components can be found in the Jdavmail package in the Lib directory, the package also includes the compiled JAR file and all the source code.
To give you a general idea of Jdavmail, here are two pieces of code that we can use to send and receive a Hotmail email:

1. Mail Collection

/*
* FileName: Hotmaildemo.java
* Date Created: 2004-9-14
* Created by: Liudong
*/
Package com.clickcom.mail;

Import Java.util.Date;
Import java.util.Properties;

Import Javax.mail.Folder;
Import Javax.mail.Message;
Import javax.mail.Session;
Import Javax.mail.Store;
Import Javax.mail.Transport;
Import javax.mail.internet.InternetAddress;
Import Javax.mail.internet.MimeMessage;

/**
* The transceiver for Hotmail mail
* @author Liudong
*/
public class Hotmaildemo {
public static void Main (string[] args) {
Receive ();
}

/**
* Mail Reception
*/

protected static void receive () {
try {
Properties prop = new properties ();
Session ses = session.getinstance (prop);
Using Jdavmail Provider
Store store = Ses.getstore ("Davmail");
No server address specified
Store.connect (NULL, "Your account", "password");
if (store.isconnected ()) {
Folder Inbox = Store.getfolder ("Inbox");
if (inbox.exists ()) {
Inbox.open (folder.read_only);
int ncount = Inbox.getmessagecount ();
System.out.println ("Inbox contains" + ncount + "messages");
Display each message in your Inbox in turn
for (int i=1;i<=ncount;i++) {
MimeMessage msg = (mimemessage) inbox.getmessage (i);
System.out.println ("Subject:" + msg.getsubject ());
System.out.println ("From:" + msg.getfrom () [0].tostring ());
System.out.println ("Content type:" + msg.getcontenttype ());
System.out.println (Msg.getcontent ());
}
}
}
catch (Exception ex) {
Ex.printstacktrace ();
}
}
}

From the above code we find that in addition to the store store = Ses.getstore ("Davmail"); This statement, without the need to specify a server address, is not the same as a common javamail application, nor does it introduce any class related to Jdavmail. No server address specified this is easier to understand because Hotmail provides a fixed address for the HTTPMail service. In fact, there's only getstore this statement is a bit different from a regular mail client, because it uses the Davmail string as a parameter, and we specify the parameter value as POP3 when we use the JavaMail connection POP3 the server. What's going on? Because the JavaMail is loaded by the protocol name to the provider class. Opening Jdavmail.0.9.006.jar This jar file will find a file javamail.providers in the Meta-inf directory, which reads as follows:

Protocol=davmail;
Type=store; Class=com.posisoft.jdavmail.jdavmailstore;
Vendor=positive Software;
Protocol=davmail_xmit;
Type=transport;
Class=com.posisoft.jdavmail.jdavmailtransport;
Vendor=positive Software;

So when we specify the protocol name Davmail, JavaMail automatically loads the Com.posisoft.jdavmail.JDAVMailStore class for processing, so the store instance obtained by passing in the Davmail string is actually a class Com.posisoft.jdavmail.JDAVMailStor An example of E, so I think you should understand how the previous procedure works.

Let's take a look at the code snippet that Jdavmail sent the message:

/**
* Send mail
*/
protected static void Send () {
try {
Properties prop = new properties ();
Mail Sender Address
Prop.setproperty ("Mail.davmail.from", "abc@hotmail.com");
Session ses = session.getinstance (prop);
Get Jdavmail Mail Send instance
Transport transport = Ses.gettransport ("Davmail_xmit");
To connect to a Hotmail server, replace it with your own username and password
Transport.connect (NULL, "username", "password");

Prepare the message to be sent
MimeMessage txmsg = new MimeMessage (SES);
Txmsg.setsubject ("This is the subject");

Mail Sender Address
InternetAddress addrfrom = new InternetAddress ("abc@hotmail.com");
Txmsg.setfrom (Addrfrom);

Mail Recipient Address
InternetAddress Addrto = new InternetAddress ("cdef@hotmail.com", "cdef");
Txmsg.addrecipient (Message.RecipientType.TO, Addrto);

Message content
Txmsg.settext ("Hello world!");
Txmsg.setsentdate (New Date ());

Send mail
Transport.sendmessage (Txmsg, txmsg.getallrecipients ());
catch (Exception ex) {
Ex.printstacktrace ();
}
}

The same code uses the Davmail_xmit protocol to get jdavmail mail-sending instances, It is not difficult to know by using the Javamail.providers file mentioned earlier that Jdavmail uses class Com.posisoft.jdavmail.JDAVMailTransport to send mail.

In the actual test found that, whether it is Jdavmail or other mail tools, the use of Hotmail to send the message is slow, almost a few minutes before receiving the appropriate information, so if the test found that the problem please be patient.

I would like to explain how to use Jdavmail to send and receive Hotmail mail, as well as study Jdavmail source code, not only can more in-depth understanding of the JavaMail architecture, to write JavaMail provider also have more specific references. Also want to solve problems for friends who are stranded in a Java program to access Hotmail mail. At the same time also very welcome through my website http://www.javayou.com to communicate with me in the use of the problems encountered.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.