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 = 
        url.openConnection();
      PrintStream   out  = 
        new PrintStream(conn.getOutputStream(), true);

      out.print(
        "From: jguru-fan@yourisp.com"+"
");
      out.print(
        "Subject: Works Great!"+"
");
      out.print(
        "Thanks for the example - it works great!"+"
");
      out.close();
      System.out.println("Message Sent");
    } catch (IOException e) {
      System.out.println("Send Failed");
      e.printStackTrace();
    }
  }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact