-1

I am trying to write a program using java that will send an email. I am using JDK 1.6.0_43 I am getting java.net.UnknownHostException: mailhost error. My code is as follows -

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

public class SendMail {
  public static void main(String[] args) {
    try {
     if (args.length >= 1) 
           System.getProperties().put("mail.host", args[0]);
     BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
     System.out.print("From: ");
     String from = in.readLine();
     System.out.print("To: ");
     String to = in.readLine();
     System.out.print("Subject: ");
     String subject = in.readLine();
     URL u = new URL("mailto:" + to);       
     URLConnection c = u.openConnection(); 
     c.setDoInput(false);                  
     c.setDoOutput(true);                  
     System.out.println("Connecting...");  
     System.out.flush();                   
     c.connect();                          
     PrintWriter out = new PrintWriter(new OutputStreamWriter(c.getOutputStream()));


    out.println("From: \"" + from + "\" <" + System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName() + ">");
    out.println("To: " + to);
    out.println("Subject: " + subject);
    out.println();  

    System.out.println("Enter the message. " + "End with a '.' on a line by itself.");
    String line;
    for(;;) {
        line = in.readLine();
         if ((line == null) || line.equals(".")) 
             break;
         out.println(line);
    }
    out.close();
    System.out.println("Message sent.");
    System.out.flush();
}
catch (Exception e) {  
  System.err.println(e);
  System.err.println("Usage: java SendMail [<mailhost>]");
    }
  }
}

How to solve this?

vegemite4me
  • 6,621
  • 5
  • 53
  • 79
Saurabh Deshpande
  • 1,153
  • 4
  • 18
  • 35

1 Answers1

0

The error message says it all: Usage: java SendMail [<mailhost>]

You need to know the name (or IP address) of your mail server. So try executing it like this:

java SendMail smtp.example.com

vegemite4me
  • 6,621
  • 5
  • 53
  • 79