JavaMail accessing hotmail mailboxes

Time:2022-1-4

I believe many people have accounts for MSN chat tools, such as [email protected] In fact, this account is also an email address, which can perform normal email sending and receiving functions. You can use the website http://www.hotmail.com To access and operate this mailbox for mail sending and receiving. However, one limitation of this mailbox is that it does not provide POP3 or SMTP services, that is, ordinary mail client tools cannot use this mailbox. Although many mail tools can support hotmail mailbox, if we need to add support for hotmail mailbox in our java project, we often don’t know where to start, Because JavaMail provided by sun does not support other protocols except POP3 / imap and SMTP.

But in fact, JavaMail only defines a set of platform independent and communication protocol independent mail program framework, or interface, which exists as an optional package of Java. Therefore, it can be said that JavaMail does not care about the protocols used, whether POP3, SMTP, IMAP or, of course, the HTTP protocol used by hotmail. The same is true for JavaMail clients. The following figure is the simplest JavaMail structure diagram, which sends mail through transport and receives mail through store. For the implementation of different protocols, the concept in JavaMail is called provider, which only needs to implement its own provider according to the interface defined by JavaMail.

JavaMail accessing hotmail mailboxes

In order to access hotmail mailbox through JavaMail, we need to build a bridge between JavaMail interface and the access interface provided by hotmail service. Before that, we must first understand the interface protocol used by hotmail.

Hotmail via address http://services.msn.com/svcs/hotmail/httpmail.asp It provides services based on HTTP protocol, which is different from our access through browser http://www.hotmail.com The latter address provides users with a browser based access interface to operate the mailbox. Of course, you can parse the page and obtain the mail information by writing an HTTP client program, but this is not only very complex, but also the program needs to be adjusted each time the page style changes, Therefore, it is obviously infeasible not to have universality. And address http://services.msn.com/svcs/hotmail/httpmail.asp It provides a fixed application program interface. When you use the browser to access the address, the following form for login will pop up:

JavaMail accessing hotmail mailboxes
After entering the correct user name and password, the prompt window will pop up again or twice, but the prompt information is different. After the operation is completed, an error that cannot be displayed on the page appears, and 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 application programming interface based on HTTP protocol. WebDAV (WEB distributed authoring and version control) has become an important web communication protocol. WebDAV aims to solve the following problems:

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

  2. Resource Management: http can only directly access a single resource. WebDAV provides a way to organize data more effectively. WebDAV introduces the concept of collections that can contain resources (similar to file system folders). Resource management through WebDAV includes the following functions: creating, moving, copying and deleting collections, as well as resources or files in collections.

  3. Document properties: different types of data have unique properties, which helps to describe the data. For example, in an e-mail message, these attributes might be the sender’s name and when the message was received. In a collaborative document, these attributes may be the name of the original author of the document and the name of the last editor. Because people use different document types, the list of possible attribute types becomes infinite. XML is an extensible communication tool required by WebDAV.

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

Compared with self parsing hotmail browser pages, the interface based on specific protocol WebDAV makes the implementation of hotmail mail client program more stable and reliable. After understanding the basic interface of JavaMail API and the protocol of the interface provided by Hotmail, the topic of this article becomes very specific, that is, if you write a JavaMail provider (JavaMail provider) based on WebDAV and use this provider to realize hotmail mail mail sending and receiving function, but this topic is too large and has exceeded the scope of an article, Therefore, we will introduce an open source project jdavmail, and introduce in detail how to realize the function of sending and receiving hotmail mail through this project.

Jdavmail is an open source JavaMail provider project, through which you can access mail services based on WebDAV protocol, such as hotmail mailbox. You can go there http://sourceforge.net/projects/jdavmail Download the latest version of the program from this website. Jdavmail uses the Commons httpclient on Jakarta as an HTTP client component to communicate with the server, and uses JDOM to parse XML data. In addition, because the httpclient project uses commons logging for journal output, commons logging is also necessary. These three components can be found in the Lib directory in the compressed package of jdavmail, The compressed package also includes compiled jar files and all source code.
In order to give you a general understanding of jdavmail, here are two pieces of code for sending and receiving hotmail mail:

  1. Mail collection

  /*
* file name: hotmaildemo java
* created on: September 14, 2004
* 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;

  /**
* 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);
/ / use jdavmail provider
   Store store = ses.getStore(“davmail”);
/ / no 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 message in the 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 except store = SES getStore(“davmail”); This statement does not need to specify the server address. Except that it is no different from an ordinary JavaMail application, it does not introduce any classes related to jdavmail. It is easy to understand that the server address is not specified, because the address of hotmail providing httpmail service is fixed. In fact, only the getstore statement is a little different from the regular mail client program in that it uses the davmail string as the parameter, and when we use JavaMail to connect to the POP3 server, we specify the parameter value as POP3. What’s going on? Because JavaMail loads the provider class through the protocol name. Open jdavmail 0.9.006. Jar this jar file will find a JavaMail. Jar file in the meta – inf directory Providers, the contents of this file are 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;

Therefore, when we specify the protocol name as davmail, JavaMail will automatically load com posisoft. jdavmail. The jdavmailstore class handles this, so the store instance obtained by passing in the davmail string is actually a com. Class posisoft. jdavmail. An example of jdavmailstore, so I think you should understand the working principle of the previous program.

Let’s look at the code snippet of sending mail by jdavmail:

  /**
* mail sending
  */
  protected static void send() {
  try {
  Properties prop = new Properties();
/ / mail sender address
  prop.setProperty(“mail.davmail.from”,”[email protected]”);
  Session ses = Session.getInstance(prop);
/ / get the mail sending instance of jdavmail
  Transport transport = ses.getTransport(“davmail_xmit”);
/ / to connect to the hotmail server, please replace it with your user name and password
  transport. Connect (null, “user name”, “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(“[email protected]”);
  txMsg.setFrom(addrFrom);

/ / mail recipient address
  InternetAddress addrTo = new InternetAddress(“[email protected]”, “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();
  }
  }

This code also uses davmail_ Xmit protocol to get the mail sending instance of jdavmail through the JavaMail Providers file is not difficult to know that jdavmail uses class com posisoft. jdavmail. Jdavmailtransport is used to send mail.

In the actual test, it is found that whether jdavmail or other mail tools, the speed of sending mail using hotmail is relatively slow, and the corresponding information can be received almost a few minutes later. Therefore, if this problem is found in the test, please wait patiently.

I want to introduce how to use jdavmail to send and receive hotmail mail, and study the source code of jdavmail, which can not only have a deeper understanding of the architecture of JavaMail, but also have a more specific reference for writing JavaMail provider. In addition, I hope to solve problems for friends who are struggling with how to access hotmail mail mail in Java programs. Also very welcome through my website http://www.javayou.com Communicate with me about the problems encountered in use.

Recommended Today

Reactor of event consumers – event traceability

This article is reproduced from [how to decouple]:https://codedecoupled.com/php… Reactor andProjectorThe only difference is that we can’t replay reactor’s behavior. Therefore, reactor is a behavior with side effects in the processing field. So what is the behavior with side effects? If the result of a behavior occurring once is different from that occurring many times, this […]