我正在使用Eclipse LUNA包。我需要从我的Java程序发送一封电子邮件。在运行该程序时,抛出了异常。
package a1;
import java.io.*;
import java.net.*;
public class a4 {
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>]");
}
}
}
运行此程序时抛出异常。我的输出屏幕如下......
From: skalyanasundaram1994@gmail.com
To: bharani829@gmail.com
Subject: hai
Connecting...
java.net.UnknownHostException: mailhost
Usage: java SendMail [<mailhost>]
答案 0 :(得分:1)
您在命令行中指定“mailhost”,它不是服务器的有效DNS名称。
您需要指定愿意在端口25上为您的应用程序提供服务的邮件服务器的名称或IP号。
答案 1 :(得分:0)
从您的输出中,您的mail.host
默认为mailhost
,而您的系统无法解决此问题。在大多数公司,它类似于smtp.example.com
,但请咨询当地的电子邮件管理员,了解哪些对您的环境有效。