通过程序发送电子邮件

时间:2014-02-20 06:48:08

标签: java email send

我正在尝试使用将发送电子邮件的java编写程序。我使用的是JDK 1.6.0_43 我收到java.net.UnknownHostException: mailhost错误。我的代码如下 -

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>]");
    }
  }
}

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

错误消息说明了所有内容:Usage: java SendMail [<mailhost>]

您需要知道邮件服务器的名称(或IP地址)。所以尝试执行它:

java SendMail smtp.example.com