Java Reference
In-Depth Information
Example 5•2: GetURLInfo.java (continued)
}
}
Sending Email Through a URLConnection
As I mentioned earlier, Java includes support for different URL protocols through
protocol handlers that are implemented internally to the Java SDK. These handlers
include support for the mailto: protocol. Example 5-3 shows a program that uses a
mailto: URL to send email. The program prompts the user to enter the sender,
recipient or recipients, subject, and body of the message, and then creates an
appropriate mailto: URL and obtains a URLConnection object for it. The program
uses the setDoInput() and setDoOutput() methods to specify that it is writing
data to the URLConnection . It obtains the appropriate stream with getOutput-
Stream() and then writes the message headers and body to that stream, closing
the stream when the message body is complete. The program uses the user.name
system property and the InetAddress class to attempt to create a valid return
address for the sender of the email, though this doesn't actually work correctly on
all platforms.
In order for the mailto: protocol handler to send mail, it must know what com-
puter, or mailhost, to send it to. By default, it attempts to send it to the machine
on which it is running. Some computers, particularly Unix machines on intranets,
work as mailhosts, so this works fine. Other computers, such as PCs connected to
the Internet by a dialup connection, have to specify a mailhost explicitly on the
command line. For example, if your Internet service provider has the domain
name isp.net , the appropriate mailhost is often mail.isp.net . If you specify a mail-
host, it is stored in the system property mail.host , which is read by the internal
mailto: protocol handler.
Note that Example 5-3 uses the println() method to display messages to the con-
sole but uses the print() method and explicit “\n” line terminator characters to
send text over the network. Different operating systems use different line termina-
tors, and println() uses whatever terminator is expected on the local system.
Since most network services originated in the Unix world, however, they typically
use the Unix line terminator, which is the “\n” newline character. We use it explic-
itly here, so that this client program works correctly when run on Unix, Windows,
or Macintosh systems.
Example 5•3: SendMail.java
package com.davidflanagan.examples.net;
import java.io.*;
import java.net.*;
/**
* This program sends e-mail using a mailto: URL
**/
public class SendMail {
public static void main(String[] args) {
try {
// If the user specified a mailhost, tell the system about it.
Search WWH ::




Custom Search