How can I use the mailto: protocol from URL or URLConnection?

Tim Rohaly

Both URL and URLConnection act as mail user agents when using the mailto: protocol. They need to connect to a mail transfer agent to effect delivery. An MTA, for example sendmail, handles delivery and forwarding of e-mail.

Note that a mailto: URL doesn't contain any information about where this MTA is located - you need to specify it explicitly by setting a Java system property on the command line. For example, to run the program mailto.java shown below, you would use the command:

    java -Dmail.host=mail.yourisp.net mailto
This tells the mailto: protocol handler to open a socket to port 25 of mail.yourisp.net and speak SMTP to it. You should of course substitute the name of your own SMTP server in the above command line.

import java.io.*;
import java.net.*;

public class mailto {

  public static void main(String[] args) {
    try {
      URL           url  = 
        new URL("mailto:foo@bar.com");
      URLConnection conn = 
      PrintStream   out  = 
        new PrintStream(conn.getOutputStream(), true);

        "From: jguru-fan@yourisp.com"+"
        "Subject: Works Great!"+"
        "Thanks for the example - it works great!"+"
      System.out.println("Message Sent");
    } catch (IOException e) {
      System.out.println("Send Failed");