【问题标题】:Sending email through program通过程序发送电子邮件
【发布时间】: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 地址

标签: java email send


【解决方案1】:

错误信息说明了一切:Usage: java SendMail [&lt;mailhost&gt;]

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

java SendMail smtp.example.com

【讨论】:

    猜你喜欢
    • 2016-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多