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 ...

Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.