如何解决Host未知异常

时间:2017-08-20 14:38:40

标签: unknown-host

当我尝试执行此代码时...它产生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; 
            } 
        } 
    }
}

请帮助我.....我是java新手...我试图实现简单的邮件传输协议......没有编译错误....当我尝试执行此...生成了未知的主机异常....

1 个答案:

答案 0 :(得分:0)

您仍然需要在localhost上运行smtp服务器。像阿帕奇詹姆斯。或者您可以尝试使用谷歌进行测试。

尝试使用此mykong example