Home > Articles > Programming > Java

Build Your Own Java-Based Email Programs

Java's Network API can be used to build many kinds of useful Java programs, including programs that send and receive email messages. In this article, Jeff Friesen introduces you to the anatomy of an email message and shows you how to use SMTP and POP3 to send and receive email messages. You also learn about MIME's support for attachments and how to incorporate an attachment into an email message.
Like this article? We recommend

Like this article? We recommend

Socket, URI, and URL: Those concepts form the foundation on which Java's Network API rests. Because I explored the socket, URI, and URL concepts (and associated classes) in my two previous Network API articles, you might wonder what more needs to be said about the Network API. My answer: plenty.

For example, it is possible to discuss socket factories and URL protocol handlers—and even to discuss useful programs that work with sockets, URIs, and URLs. One useful program is a World Wide Web (WWW) browser that lets users view HTML pages with ease. Creating a Java-based browser is not as difficult a task as you might think because Java's class library includes two classes that work with the Network API to implement a browser for HTML (version 3.2) pages: javax.swing.JEditorPane and javax.swing.text.html.HTMLEditorKit.

Although it would be interesting to explore the creation of a Java-based WWW browser (and those classes) in this article, I will not do that because my goal is to explore electronic mail (email). Specifically, I plan to introduce you to the anatomy of an email message and then show you how to use the Network API to develop programs that send and receive email messages.

Programs typically use Simple Mail Transfer Protocol (SMTP) to send email messages and Post Office Protocol 3 (POP3) to receive email messages. Because this article provides only a brief look at those network protocols, you should read the following Request For Comments (RFC) documents (after you finish reading this article) to learn more about SMTP and POP3:

NOTE

Sun provides the high-level JavaMail API for working with email. I have chosen not to discuss that API because it is my desire to show how email works at a low level. Once you complete this article, you might want to learn more about JavaMail. To visit Sun's official JavaMail API WWW page, point your browser to http://java.sun.com/products/javamail/index.html.

Version 1.4 (beta 2) of Sun's Java 2 Standard Edition (J2SE) SDK was used to build this article's programs.

Anatomy of an Email Message

Before building your own email program, you should understand the anatomy (that is, format) of an email message. That anatomy bases itself on RFC 2822, "Internet Message Format."

According to RFC 2822, an email message consists of a sequence of lines, with each line consisting of ASCII characters (whose codes range from 1 through 127) and ending with a carriage-return character (ASCII code 13) followed by a newline character (ASCII code 10). Furthermore, the maximum length of each line (excluding the carriage-return and newline characters) is 998 characters. Various lines provide information that are important to the whole message, known as header fields (or headers, for short). Other lines provide the message's content. Figure 1 illustrates the anatomy of an email message as lines and headers/content.

Figure 1 Email message anatomy.

Headers provide information concerning the email message's origin (who sent the email message), the email message's destination (who will receive the email message), the subject of the email message, and so on. Each header is organized as a name and a colon character, followed by one or more values of relevance to that header. Some header values identify mailboxes (conceptual entities that receive email messages). Each of those mailbox values is either a display name and address specification (in which the address specification is enclosed by angle brackets) or just an address specification (not enclosed by angle brackets).

The following example illustrates a mailbox address specification followed by a mailbox display name and address specification:

Doe@x.org
John Doe <Doe@x.org>

Who sent the email message? The From:, Sender:, and Reply-To: headers provide information regarding an email message's origin. From: identifies the mailbox(es) of the email message's author(s), Sender: identifies the mailbox of the agent (person or machine) responsible for sending the email message, and Reply-To: identifies the mailbox(es) to which replies should be directed.

It is possible for an email message to have multiple authors. Therefore, the From: header specifies either a single mailbox value or a comma-delimited list of mailbox values. However, From: should not list any mailbox value that does not belong to an author.

The following example illustrates a From: header consisting of a single author's mailbox value and a From: header consisting of two authors' mailbox values.

From: John Doe <Doe@x.org>
From: Sally Smith <Smith@x.org>, Doe@x.org

It is not possible for an email message to have multiple senders. Therefore, the Sender: header specifies a single mailbox value. Furthermore, if only a single author's mailbox value is specified in the From: header, and if that mailbox value's address specification is identical to the sender mailbox value's address specification, the Sender: header should not be present (because that header is redundant). Otherwise, the Sender: header should be present (according to RFC 2822).

The following example illustrates a Sender: header that specifies a single mailbox value:

Sender: Jane Smith <JSmith@x.org>

It's possible to direct replies to multiple mailboxes. Therefore, the Reply-To: header specifies either a single mailbox value or a comma-delimited list of mailbox values. If Reply-To: is present, an email program directs its replies to all mailbox values listed by that header. However, if that header is absent, an email program directs its replies to all mailbox values listed by the From: header.

The following example illustrates a Reply-To: header that specifies three mailbox values. Replies are sent to the mailboxes identified by those values.

Reply-To: Smith@x.org, John Doe <Doe@x.org>, JSmith@x.org

Who will receive the email message? The To: and Cc: headers provide information about an email message's destination. To: specifies the primary recipient(s) of the message, and Cc: (carbon copy) specifies the secondary recipient(s). For each header, either a single mailbox value or a comma-delimited list of mailbox values appears as part of that header.

The following example illustrates To: and Cc: headers. The To: header specifies a single mailbox value for the primary recipient and the Cc: header specifies two mailbox values for the secondary recipients.

To: Jeff Friesen <jeff@javajeff.com>
Cc: Smith@x.org, Doe@x.org

TIP

When an email message is being turned into a reply, place Reply-To: mailbox values (if present) in the To: header. Otherwise, use From: mailbox values.

RFC 2822 presents many headers besides the originator and receiver headers. For example, the Subject: header provides an optional title for an email message. That means that a sequence of ASCII characters can follow Subject: and a colon character, and that a sequence of ASCII characters serves as the email message's title.

The following example illustrates a Subject: header in context with other headers:

From: John Doe <Doe@x.org>
To: Jeff Friesen <jeff@javajeff.com>
Cc: Bill Jones <jones@x.org>
Subject: Accounting Details

The example shows that John Doe is authoring an email message, the email message is destined for Jeff Friesen's mailbox at jeff@javajeff.com, Jeff Friesen is the primary recipient, Bill Jones (jones@x.org) is the secondary recipient, and the subject of the email message is Accounting Details.

Attachments

The previous article introduced you to Multipurpose Internet Mail Extensions (MIME). MIME lets an email program attach a file of binary data to an email message, which is known as an attachment, and transmit that file's contents as part of the email message. MIME accomplishes that task by introducing a variety of headers. The most important headers for attachments are Content-Type: (which classifies the type and subtype of data that serves as an email message's content) and Content-Transfer-Encoding: (which specifies an encoding of 8-bit binary data to 7-bit ASCII data).

Among the various types and subtypes that can be specified in the Content-Type: header, MIME reserves type multipart and subtype mixed for attachments. That type/subtype combination signifies content broken up into multiple body parts, with each body part representing an attachment and having its own Content-Type: and Content-Transfer-Encoding: headers. To help an email program differentiate a body part from the next body part, MIME requires a sending email program to include a boundary parameter as part of the Content-Type: multipart/mixed header. boundary's value (between double-quote characters) is a character sequence that delimits a body part from the next body part. Before transmitting a body part, an email program transmits a carriage-return character, a newline character, two hyphen characters, and boundary's value—a character sequence known as an encapsulation boundary. Following the final body part, an email program transmits an encapsulation boundary and two hyphens (--).

The following code fragment identifies a plain-text email message with characters taken from the iso-8859-1 character set, and a plain-text attachment that associates its contents with file.txt. Content-Transfer-Encoding:'s absence implies default 7BIT ASCII.

Content-Type: multipart/mixed; boundary="***"

--***
Content-Type: text/plain; charset="iso-8859-1"

This message has an attachment.

--***

Content-Type: text/plain; name="file.txt"

Attachment text.

--***--

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