unknown-host

how to solve Host unknown exception


when i try to execute this code ...It produces the hostunknownException....

     import java.io.*; 
     import java.net.*;
     import java.net.Socket; 
     public class SMTP
     { 
      public static void main(String[] args) //throws Exception 
    { 
        String results = send("sender@somewhere.com", "localhost/localdomain", "Test Email", "<b>You got mail!</b>"); 
        System.out.println(results); 
    } 
    public static String send(String from,String to,String subject, String message) //throws Exception 
    { 
        StringBuffer buffer = new StringBuffer(); 
        try 
        { 
            Socket smtpSocket = new Socket("127.0.0.1",25); 
            DataOutputStream output = new DataOutputStream(smtpSocket.getOutputStream()); 
            BufferedReader input =new BufferedReader(new InputStreamReader( new DataInputStream(smtpSocket.getInputStream()))); 
            try 
            { 
                read(input, buffer); 
                send(output, "HELO localhost.localdomain\r\n", buffer); 
                read(input, buffer); 
                send(output, "MAIL FROM: " + from + "\r\n", buffer); 
                read(input, buffer); 
                send(output, "RCPT to: " + to + "\r\n", buffer); 
                read(input, buffer); 
                send(output, "DATA\r\n", buffer); 
                read(input, buffer); 
                send(output, "Subject: " + subject + "\r\n", buffer); 
                send(output, message, buffer); 
                send(output, "\r\n.\r\n", buffer); 
                read(input, buffer); 
                smtpSocket.close(); 
            } 
            catch (IOException e) 
            {
                System.out.println("Cannot send email as an error occurred."); 
            }
        } 
        catch (Exception e) 
        {
            System.out.println("Host unknown"); 
        }
        return buffer.toString(); 
    } 
    private static void send(DataOutputStream output,String data,StringBuffer buffer) throws IOException 
    { 
        output.writeBytes(data); 
        buffer.append(data); 
    } 
    private static void read(BufferedReader br, StringBuffer buffer) throws IOException 
    { 
        int c;
        while ((c = br.read()) != -1)
        {
            buffer.append((char) c);
            if (c == '\n')
            { 
                break; 
            } 
        } 
    }
}

Please help me.....i'm new to java...i trying to implement the simple mail transfer protocol...there is no compilation errors....when i try to execute this ...unknown host exception is produced....


Solution

  • You still need a smtp server running on your localhost. Like apache James. Or you could try using google ones for testing purpose.

    Try with this mykong example