O'Reilly logo

Java Examples in a Nutshell, 3rd Edition by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Sending Email Through a URLConnection

As 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 getOutputStream( ) 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 computer, 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required