Home > Articles > Programming > Java

Like this article? We recommend

Like this article? We recommend

Receiving an Email Message

Internet-based email messages are typically received from senders by way of the POP3 network protocol. According to POP3, when an email program needs to receive email messages, that program establishes a two-way transmission channel (by way of sockets) to a POP3 server program that is always running on some accessible host (such as your Internet Service Provider's host). Once the email and POP3 server programs have established a two-way transmission channel, the email program issues a sequence of ASCII-based commands to the POP3 server program, and the POP3 server program replies to each command with an ASCII-based response message indicating success or failure. Initial commands identify a user's mailbox within the SMTP/POP3 email database and authenticate the user wanting to access his mailbox. Assuming successful authentication, the POP3 server program accepts email message retrieval commands from the email program and returns specified email messages (from the user's mailbox) to the email program. Figure 3 provides an illustration of this POP3 model.

Figure 3 The POP3 model for receiving email messages. Sockets appear as green boxes.

POP3 recognizes a variety of commands that email programs can use to communicate with POP3 server programs. Some commands take arguments and other commands take no arguments, but each command must end with a carriage-return character followed by a newline character. Six commonly used commands are USER, PASS, STAT, RETR, DELE, and QUIT.

The previous ordering of the six commonly used POP3 commands is not an accident. The commands must be entered in their specified order (although STAT, RETR, and DELE can be entered in any order, as long as they are entered after PASS and before QUIT) because a POP3 server program is a state-based program. For each email program that establishes a two-way transmission channel with the POP3 server program, the POP3 server program maintains username/password state on the current email message transaction with that email program.

When an email program successfully connects its socket to a POP3 server program's server socket, the POP3 server program sends an initial message to the email program. That message consists of a +OK reply code and a text message identifying the SMTP server program.

The reply code, which is located at the beginning of every POP3 server program response message, is either +OK for success or -ERR for failure; this is used by email programs to automate their email message transactions with POP3 server programs. By contrast, the text message provides meaningful information to a user. An email program must check the reply code to determine its next course of action, but it may ignore the text message if it is not deemed to be relevant (such as the initial message).

After receiving the initial message, an email program begins its email message transaction by sending the USER command. USER identifies the name of the user requesting access to the user's mailbox and takes an argument that identifies the user's name. In response, the POP3 server program validates the existence of a mailbox corresponding to the specified username. Either +OK or -ERR, with a suitable message, returns to the email program.

Following USER, an email program sends the PASS command. PASS identifies the password that associates with the previously specified username. If the password is correct, the POP3 server program returns a response message beginning with +OK. Otherwise, a response message that begins with -ERR returns.

At this point, the email program is free to issue the STAT, RETR, and DELE commands (in any order) to obtain statistics on the number of messages and message size (in bytes, also known as octets), to retrieve email messages, and to delete email messages (respectively).

The STAT command takes no arguments, and its +OK x y response identifies x waiting messages having a combined size of y bytes.

Both the RETR and DELE commands take a single one-based integer argument that identifies an email message. When the email program sends the RETR command, the POP3 server program replies with a -ERR response message if there is no email message associated with the integer argument. Otherwise, the POP3 server program replies with a multiline response message, beginning with +OK y, where y identifies the total number of bytes in remaining lines. The email program must continue reading lines from the POP3 server program until it reads a line beginning with a period character (or the total number of bytes has been read, whichever comes first). That final line signifies the end of RETR's response. When the email program sends the DELE command, the POP3 server program replies with a -ERR response message if there is no email message associated with the integer argument, or a +OK response message that confirms email message deletion.

Finally, when the time comes to disconnect its transmission channel with the POP3 server program, the email program sends the no-argument QUIT command.

To help you understand POP3-based email transactions, I wrote a command line–based program called POP3Demo. When run, that program attempts to connect to my ISP's POP3 server program on standard port number 110. Although you should not need to change 110 (because that number is standard for a POP3 server program port), you will need to change mail.gatewest.net to the domain name of your ISP's host (so that the program will work for you) before compiling POP3Demo's source code. Listing 2 presents that source code.

Listing 2: POP3Demo.java

// POP3Demo.java

import java.io.*;
import java.net.*;

class POP3Demo
{
  public static void main (String [] args)
  {
   String POP3Server = "mail.gatewest.net";
   int POP3Port = 110;

   Socket client = null;

   try
   {
     // Attempt to create a client socket connected to the POP3 
     // server program.

     client = new Socket (POP3Server, POP3Port);

     // Create a buffered reader for line-oriented reading from the
     // standard input device.

     BufferedReader stdin;
     stdin = new BufferedReader (new InputStreamReader (System.in));

     // Create a buffered reader for line-oriented reading from the
     // socket.

     InputStream is = client.getInputStream ();
     BufferedReader sockin;
     sockin = new BufferedReader (new InputStreamReader (is));

     // Create a print writer for line-oriented writing to the 
     // socket.

     OutputStream os = client.getOutputStream ();
     PrintWriter sockout;
     sockout = new PrintWriter (os, true); // true for auto-flush

     // Display POP3 greeting from POP3 server program.

     System.out.println ("S:" + sockin.readLine ());

     while (true)
     {
      // Display a client prompt.

      System.out.print ("C:");

      // Read a command string from the standard input device.

      String cmd = stdin.readLine ();

      // Write the command string to the POP3 server program.

      sockout.println (cmd);

      // Read a reply string from the POP3 server program.

      String reply = sockin.readLine ();

      // Display the first line of this reply string.

      System.out.println ("S:" + reply);

      // If the RETR command was entered and it succeeded, keep
      // reading all lines until a line is read that begins with 
      // a . character. These lines constitute an email message.

      if (cmd.toLowerCase ().startsWith ("retr") &&
        reply.charAt (0) == '+')
        do
        {
          reply = sockin.readLine ();
          System.out.println ("S:" + reply);
          if (reply != null && reply.length () > 0)
            if (reply.charAt (0) == '.')
              break;
        }
        while (true);

      // If the QUIT command was entered, quit.

      if (cmd.toLowerCase ().startsWith ("quit"))
        break;
     }
   }
   catch (IOException e)
   {
     System.out.println (e.toString ());
   }
   finally
   {
     try
     {
      // Attempt to close the client socket.

      if (client != null)
        client.close ();
     }
     catch (IOException e)
     {
     }
   }
  }
}

After you replace mail.gatewest.net with your ISP's hostname and compile POP3Demo's source code, type java POP3Demo. Carry out the following exercise, and you will see similar output:

The following exercise's output is from a sample session between myself (C:) and my ISP's POP3 server program (S:).

S:+OK QPOP (version 2.3) at kynes.gatewest.net starting. 
<27402.1015108737@kynes.gatewest.net>

This initial message was sent from my ISP's Linux-based QPOP POP3 server program to POP3Demo.

C:user jeff
S:+OK Password required for jeff.

I began the email message transaction by typing user jeff, to identify my mailbox. QPOP replied with a +OK response message indicating that it is waiting for a password.

C:pass ********
S:+OK jeff has 1 message (554 octets).

I next specified my password. Although you see eight asterisks, I did not type those asterisks: I entered my actual password, instead. In response, QPOP sent a +OK message identifying one email message in my mailbox and also identifying the email message's size as 554 octets (bytes).

C:retr 1
S:+OK 554 octets
S:Return-Path: <jeff@javajeff.com>
S:Received: from gatewest.net (h139-142-224-80.gtcust.grouptelecom.net 
[139.142.224.80]
S:    by kynes.gatewest.net (8.12.1/8.12.0.Beta19/Debian 
8.12.0.Beta19)
S:    for <jeff@javajeff.com>; Sat, 2 Mar 2002 16:38:29 -0600
S:Date: Sat, 2 Mar 2002 16:38:10 -0600
S:From: Jeff Friesen <jeff@javajeff.com>
S:Message-Id: <200203022238.g22McAxW027265@kynes.gatewest.net>
S:Subject: Test Email
S:To: undisclosed-recipients:;
S:X-UIDL: ef17608650892dac19191c3244fbe4a9
S:
S:This is my email message.
S:
S:.

I decided to retrieve that email message by specifying retr 1. (I chose 1 as an argument to RETR because there was only one email message and because email message numbers begin with 1.) In response, I received lots of information. Note the g22McAxW027265 message ID. That ID identifies this email message as the first email message that I sent during my demonstration of SMTPDemo.

It might surprise you to see a From: header in the retrieved email message. After all, I did not specify a From: header when I sent the email message. From where did From: originate? When I sent the email message with SMTPDemo, my ISP's SMTP server program provided that header (starting with information gleaned from the MAIL command). You might also be surprised to see a To: undisclosed-recipients:; header because I did not specify that header when sending the email message. In the absence of To: or Cc: headers, my ISP's POP3 server program provided that header (to hide RCPT addresses).

C:dele 1
S:+OK Message 1 has been deleted.

After reading my email message, I decided to delete it from my mailbox by specifying dele 1. The +OK response message indicates successful deletion:

C:stat
S:+OK 0 0

Just to confirm that my mailbox was empty, I sent the STAT command to the QPOP POP3 server program. QPOP responded with a +OK message indicating no email messages in my mailbox:

C:quit
S:+OK Pop server at kynes.gatewest.net signing off.

After retrieving and deleting the email message, I had nothing else to do, so I terminated my connection with the QPOP POP3 server program.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020