【发布时间】:2014-03-20 22:52:59
【问题描述】:
我正在尝试使用 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>]");
}
}
}
如何解决?
【问题讨论】:
-
请编辑您的问题g以包含异常的堆栈跟踪
-
先包含异常的详细信息怎么样...
-
错误很明显,
mailhost是一个有效的主机吗? -
@Prradeep - 你能探索一下吗?我是新手......我应该写什么而不是
mailhost -
您也可以用不同的方式发送它stackoverflow.com/questions/3649014/send-email-using-java?rq=1... mailHost 表示您的 SMPTP 服务器 IP 地址