JavaMail access Hotmail

Source: Internet
Author: User

I believe many people have MSN chat tools account, such as abc@hotmail.com, this account is actually a mail address, can be normal mail sending and receiving function, you can access and operate this mailbox through the Web site http://www.hotmail.com for mail sending and receiving. However, this mailbox has a restriction that it does not provide POP3 or SMTP services. That is to say, this mailbox cannot be used by common mail client tools. Although many Mail tools currently support Hotmail, however, if we need to add support for Hotmail in our Java project, we often do not know where to start, because the JavaMail provided by SUN does not support POP3, IMAP, and SMTP protocols.

But in fact, JavaMail only defines a set of mail program frameworks that are platform-independent and independent from communication protocols, or interfaces. It exists as an optional Java package. So it can be said that JavaMail does not care about the protocols used, whether it is POP3, SMTP, IMAP, or the HTTP protocol used by Hotmail. This is also true for the JavaMail client. It is the simplest JavaMail structure. It sends emails through Transport and collects emails through Store. Different protocols are implemented, the concept in JavaMail is Provider. You only need to implement your own Provider according to the interface defined by JavaMail.


To access Hotmail via JavaMail, we need to build a bridge between the JavaMail interface and the access interface provided by the Hotmail service. Before that, we must first understand the interface protocol used by Hotmail.

Hotmail provides HTTP-based services through the address http://services.msn.com/svcs/hotmail/httpmail.asp, which is different from the address where we access the http://www.hotmail.com through a browser, the following address provides a browser-based access interface for you to operate on your mailbox. Of course, you can write an HTTP client program to parse the page and obtain mail information, however, this not only achieves a very high degree of complexity, but also requires corresponding adjustments to the program after each page style change. Therefore, it is not universal and obviously not feasible. Unlike address http://services.msn.com/svcs/hotmail/httpmail.asp, it provides a fixed application interface. When you use a browser to access this address, the following Logon Request Form is displayed:


When you enter the correct user name and password, the prompt window is displayed again or twice, but the prompt information is different. After the operation is complete, an error cannot be displayed on the page, the error code is 405 (the resource is not allowed ). Therefore, this service cannot be accessed through a browser.

In fact, Hotmail uses WebDAV to provide HTTP-based application programming interfaces. WebDAV (Web Distributed creation and version control) has become an important Web communication protocol. WebDAV solves the following problems:

1. Rewrite protection: HTTP 1.1 cannot ensure that the client can protect resources and make changes when other clients edit them at the same time. WebDAV can be used to lock resources in multiple ways, so that other clients can know that you are interested in the resources discussed, or prevent other clients from accessing the resources.

2. Resource Management: HTTP can only directly access a single resource. WebDAV provides a more effective way to organize data. WebDAV introduces a collection of resources (similar to a file system folder. Resource management through WebDAV includes the following functions: creating, moving, copying, and deleting a set, and resources or files in the set.

3. document attributes: different types of data have unique attributes, which helps describe data. For example, in an email, these attributes may be the sender's name and receipt time. In a collaboration document, these attributes may be the name of the original author of the document and the name of the last editer. Because different types of documents are used, the list of possible attribute types becomes infinitely large. XML is a scalable communication tool required by WebDAV.

For more information about WebDAV, refer to the final references in this article.

Compared with self-parsing Hotmail browser pages, the Hotmail client program is more stable and reliable Based on the WebDAV interface of the specific protocol. After learning about the basic interfaces of the JavaMail API and the protocols of the interfaces provided by Hotmail, the question of this article becomes very specific, that is, if you compile the JavaMail Provider based on WebDAV (JavaMail Provider) and use this provider to implement the Hotmail mail sending and receiving function, but this topic is too large and beyond the scope described in an article. Therefore, we will introduce an open source code project JDAVMail, it also describes in detail how to use this project to send and receive Hotmail messages.

JDAVMail is an open-source JavaMail provider project that can be used to access WebDAV-based mail services, such as Hotmail. You can go to the http://sourceforge.net/projects/jdavmail web site to download the latest version of the program. JDAVMail uses commons httpclient on Jakarta to communicate with the server as an HTTP client component, and uses jdom to parse XML data. In addition, the httpclient project uses commons logging to output logs, therefore, commons-logging is required. These three components can be found in the lib directory of the JDAVMail compressed package. The compressed package also contains compiled jar files and all source code.
To give you a rough idea of JDAVMail, we will provide two pieces of code for sending and receiving Hotmail:

1. receive emails

/*
* File name: HotmailDemo. java
* Creation Time: 2004-9-14
* Creator: 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;

/**
* Hotmail email Transceiver
* @ Author liudong
*/
Public class HotmailDemo {
Public static void main (String [] args ){
Receive ();
}

/**
* Receive emails
*/

Protected static void receive (){
Try {
Properties prop = new Properties ();
Session ses = Session. getInstance (prop );
// Use JDAVMail Provider
Store store = ses. getStore ("davmail ");
// You do not need to specify the server address
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 email in the inbox in sequence
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 found that apart from Store = ses. getStore ("davmail"); this statement does not require the server address to be specified, but is similar to a common JavaMail application, no JDAVMail-related classes were introduced. It is easy to understand that no server address is specified, because the address of Hotmail to provide the HttpMail service is fixed. In fact, the getStore statement is a little different from the conventional mail client program because it uses the davmail string as the parameter, and we specify the parameter value as POP3 when connecting to the pop3 server using JavaMail. What's going on? Because JavaMail loads the Provider class through the Protocol name. Open the jar file JDAVMail.0.9.006.jar and you will find a file javamail. providers under the META-INF directory. The content of this file is 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 will automatically load com. posisoft. jdavmail. the JDAVMailStore class is processed. Therefore, the store Instance obtained by passing in the davmail string is actually a class com. posisoft. jdavmail. an example of JDAVMailStore, So that I think you should understand the working principle of the previous program.

Let's take a look at the code snippet of the JDAVMail Email:

/**
* Email sending
*/
Protected static void send (){
Try {
Properties prop = new Properties ();
// Email sender address
Prop. setProperty ("mail. davmail. from", "abc@hotmail.com ");
Session ses = Session. getInstance (prop );
// Get the JDAVMail mail sending instance
Transport transport = ses. getTransport ("davmail_xmit ");
// Connect to the Hotmail server. Replace it with your username and password.
Transport. connect (null, "User Name", "password ");

// Prepare the email to be sent
MimeMessage txMsg = new MimeMessage (ses );
TxMsg. setSubject ("This is the subject ");

// Email sender address
InternetAddress addrFrom = new InternetAddress ("abc@hotmail.com ");
TxMsg. setFrom (addrFrom );

// Email recipient address
InternetAddress addrTo = new InternetAddress ("cdef@hotmail.com", "cdef ");
TxMsg. addRecipient (Message. RecipientType. TO, addrTo );

// Email content
TxMsg. setText ("Hello world! ");
TxMsg. setSentDate (new Date ());

// Send an email
Transport. sendMessage (txMsg, txMsg. getAllRecipients ());
} Catch (Exception ex ){
Ex. printStackTrace ();
}
}

Similarly, this Code uses the davmail_xmit protocol to obtain the JDAVMail mail sending instance, through the javamail mentioned above. it is not difficult to know That JDAVMail uses the class com. posisoft. jdavmail. JDAVMailTransport sends emails.

In actual tests, it was found that no matter whether it is JDAVMail or other email tools, Hotmail was used to send emails slowly, and the corresponding information could not be received after several minutes, therefore, if this problem is found during the test, please wait patiently.

I want to introduce how to use JDAVMail to send and receive Hotmail and study the source code of JDAVMail. This not only gives me a better understanding of the architecture of JavaMail, but also provides more detailed references for compiling JavaMail providers. In addition, I hope that it will help my friends who are stuck in accessing Hotmail in Java programs to solve their problems. At the same time, I am very welcome to communicate with me through my website http://www.javayou.com problems encountered in use.

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.