Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

JVM Languages

Java Q&A


August 1996: Java Q & A

How Do I Send e-mail from a Java Applet?

Cliff Berg

Cliff, vice president of technology of Digital Focus, can be contacted at [email protected]. To submit questions, check out the Java Developer FAQ Web site at http://www.digitalfocus.com/faq/.


Client-side programming makes it possible to have interactive forms

Sending an e-mail message from a Web page is one of the most widely used CGI applications. However, most implementations rely on the existence of a particular, nonstandard CGI program on the server to interface with the mail server; thus, every time a Web site is developed, the webmaster has to investigate what, if any, CGI interface program is available and possibly write one from scratch. A Java implementation solves this problem by shifting the burden to the client side. All that is required is a mail server on the Web site host.

The e-mail systems used on the Internet are, in one sense, very simple: The send and receive protocols for mail are easy to understand and program into a client application. The actual implementation of mail servers, however, is complicated by the fact that they must interface with foreign mail systems, which may involve translation of e-mail addresses between the different formats. Amazingly, the system works pretty well.

A mail client need not worry about this. It only has to be concerned with the protocol for sending a message and, if desired, for receiving one. While it is obviously important to receive messages, this is not typically a Web application, unless you are building a full-blown e-mail client. One feature that may be useful on the client, however, is the ability to count how many messages are waiting to be retrieved. Thus, in a typical commercial Web scenario, users could have a means to send e-mail to a designated customer-service representative directly from the Web page without relying on a CGI program; conversely, the customer-service representative would have a way, via a private "administration" Web page, to monitor the site, including seeing how many messages are waiting from users.

How do Mail Servers Work?

From the e-mail client point of view, there are typically two mail servers involved: the send-mail server and the retrieve-mail (or mailbox) server. The most commonly used send-mail server in public Web installations is the UNIX "sendmail" program, which implements the protocol with mail clients for accepting new messages and sending them out onto the Internet. It also has the job of interfacing with other mail systems on the Internet. Simple Mail Transfer Protocol (SMTP) is the primary protocol used by sendmail.

In UNIX-based Web installations, the task of retrieving received messages from an electronic mailbox is typically accomplished by another server program, the Post Office Protocol (POP) server. When sendmail receives mail from the Internet, it either forwards it if the recipient is not local, or hands it over to the local mailbox server for storage and retrieval by a user. In this article, I'll interface with a POP mailbox server to see if messages are waiting to be retrieved. Aside from that, however, we will be interacting with an SMTP server.

The SendMail Applet

The Java applet for sending e-mail is called "SendMail." When users go to a Web page that has the SendMail applet on it, they see a form like that in Figure 1. The actual layout of the form can be customized by adding or removing fields in the Form class (available electronically). This is analogous to customizing an HTML form for an application. A main difference is that you have more freedom to place fields in specific locations on the page via Java's layout capabilities, whereas HTML is limited in its ability to position elements. A more sophisticated applet form could even perform calculations, rather than merely capture data.

The e-mail's destination is specified in an HTML RECIPIENT parameter. This allows for easy maintenance of the Web site, since the desired recipient may change over time, and it should not be hard-coded into the program.

Example 1(a) lists the commands that the client must send to the SMTP server. The HELO command initiates a session. MAIL FROM: tells the server what the return address is, in case the mail needs to be returned. RCPT TO: is the destination address. DATA tells the server that the following lines contain the message body, terminated by a single period on a line by itself. Each command, including the terminating period, must be followed with a line-feed. Thus, all you need to do is establish a session with the server on the correct port, send these commands and information in the right sequence, and you've sent e-mail.

The SendMail client does not need to maintain a connection to the server: It merely opens the connection when it wants to send mail, sends the mail, and closes the connection. Opening a connection in Java is accomplished by creating an instance of Socket and specifying the Internet host name and the port the SMTP server is listening on. SMTP servers use the well-known port number 25 to listen for client connections. SendMail gets the host name from the applet itself: The java.applet method Applet.getCodeBase() returns the URL of the applet, and URL.getHost() returns the name of the host.

Once a connection is established, SendMail sends each verb in turn, combined with information obtained from the form. The method Form.email() returns the information entered by the user into the "Your e-mail Address" field on the form. This is the sender's e-mail address (if they filled it out correctly). The method Form.message() returns the rest of the form's content. This includes all of the other fields, each prefaced with the name of the field so that the recipient can tell what information pertains to what field. In the CGI e-mail analogue, these would be the field nametags passed as URL-encoded parameters.

It is not too hard to design the Form class so that its content and layout are completely specified in HTML. This way, the applet never has to be recoded, and the site's administrator can make additions or changes to the form simply by changing HTML applet parameters.

Hidden tags can be included in the form as well. In the Form class, I collect the document base of the applet and send it to the server with the other message information. The document base is the URL that the applet's Web page was loaded from. Thus, the e-mail recipient receives a message that tells him or her which Web page the user was looking at when the message was sent. This may be important information if the applet is used more than once within the site. It also includes the date the applet was sent, although the trustworthiness of the date is questionable, since it comes from the end-user's system, which may not have the date or time set correctly!

The CheckMail Applet

Sometimes people receiving messages in a Web e-mail application may have multiple e-mail accounts. Therefore it may be desirable to have a way to notify them that there is mail waiting, without them having to use their e-mail program to check. An applet that allows them to check for mail may therefore be useful as part of a private site-maintenance and administration page.

The CheckMail applet (see Figure 2) presents a form to the user, and requests a user id and password. It then attempts to connect with the POP server, and if successful, queries how many messages are waiting in the user's mailbox. It then displays this information on the screen.

The design and operation of CheckMail is very similar to SendMail. The main differences are that the contents of the input form are different, and information retrieved from the server (the number of messages) is displayed. This is accomplished easily using the TextComponent.setText() method to display a string in a field. Also, the password field contents need to be cloaked so that others looking at your screen cannot see your password. For this purpose the method TextField.setEchoCharacter() sets a character to be echoed to the screen with each keystroke.

The POP verbs used are listed in Example 1(b). Again, all you have to do is open a connection to the POP server (typically listening on port 110), and send these commands in sequence; except that this time you have to parse the output sent back from the server to obtain the data you want. The number of messages in the mailbox is contained in the line of data returned after you send the STAT command. The line will be something like "+OK 3 messages..." when you have three messages waiting. The "+OK" indicates that the command was processed without any errors. An error return would start with "-ERR".

One caveat: To access your e-mail information from CheckMail, you will have to have a shell account (which gives you e-mail) on the Web machine; a POP server can only check for mail on a machine on which you have an account. Further, coding the applet to check mail by accessing a POP server on a machine other than the Web machine is not an option, since a Java applet can only open a socket connection to the same machine it was downloaded from. If the CheckMail applet returns the error "Incorrect password," it probably means that your e-mail account is not accessible on the Web machine. If your system administrator is not able to set up a shell account for you on the Web server (some service providers have this policy), an alternative is to host just the applet on a different machine on which you do have a shell account (this machine will also need to have a Web server), and point to it in your HTML with the applet codebase parameter.

Conclusion

Gathering information from visitors to a Web site is now merely a matter of modifying the Form class to collect the desired information, and placing the SendMail applet on the site. Interaction with a CGI program is not necessary. Additionally, the CheckMail applet can be used to quickly monitor e-mail sent to the site, thereby ensuring a quick reply. Again, no CGI programming is necessary. All programming is thus moved to the client side, and is platform independent.

You can find the complete source code for SendMail at http://www.ddj.com/. Source for a full-featured version that uses HTML parameters to more fully configure the applet, thus making recoding for many applications unnecessary, is available at http://www.digitalfocus.com/ ddj/code/.

Figure 1: The SendMail applet.

Figure 2: The CheckMail applet.

Example 1: (a) Commands client must send; (b) POP verbs.

(a)

HELO <your host>
MAIL FROM: <return-address>
RCPT TO: <recipient>
DATA


(b)

USER <user-id>
PASS <password>
STAT



Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.