2015-10-08 102 views
0

我试图使用this example从gmail id发送邮件到另一个邮件。这里是我的文件:MailConnectException:嵌套的异常:java.net.SocketException:权限被拒绝:连接

public class SendHTMLEmail 

    // Recipient's email ID needs to be mentioned. 
    String to = "[email protected]"; 

    // Sender's email ID needs to be mentioned 
    String from = "[email protected]"; 

    // Assuming you are sending email from localhost 
    String host = "localhost"; 

    // Get system properties 
    Properties properties = System.getProperties(); 

    // Setup mail server 
    properties.setProperty("mail.smtp.host", host); 
    properties.setProperty("mail.user", "Admin"); 
    properties.setProperty("mail.password", "admin"); 

    // Get the default Session object. 
    Session session = Session.getDefaultInstance(properties); 

    try{ 
    // Create a default MimeMessage object. 
    MimeMessage message = new MimeMessage(session); 

    // Set From: header field of the header. 
    message.setFrom(new InternetAddress(from)); 

    // Set To: header field of the header. 
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); 

    // Set Subject: header field 
    message.setSubject("This is the Subject Line!"); 

    // Send the actual HTML message, as big as you like 
    message.setContent("<h1>This is actual message</h1>", "text/html"); 

    // Send message 
    Transport.send(message); 
    System.out.println("Sent message successfully...."); 
    }catch (MessagingException mex) { 
    mex.printStackTrace(); 
    } 

我在localhost:9091端口上运行Tomcat服务器。我收到以下错误:

screen shot from cmd

我该如何解决这个问题?

回答

0

那么,你设置了“host = localhost”,这样你的程序就会尝试使用位于localhost的smtp服务器。问题是:您没有(也不想要)安装本地主机上的smtp服务器。至少看起来是这样。

我想你想要做的是:http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/

如果你想这个例子中,你需要牢记不要因为它包含硬编码的Gmail凭证发布。

+0

谢谢你的回复keocra。将尝试与建议的例子。 –

+0

它曾经工作过一次,然后我更改了发件人电子邮件。它没有工作,但现在我得到以下错误:com.sun.mail.util.MailConnectionException:无法连接到主机,端口:smtp.gmail.com,25;超时-1;嵌套异常是:java.net.UnknownHostException:smtp.gmail.com –

+0

看看你的端口和例子。我认为,通过这些信息,你应该能够解决你的问题。 – keocra

相关问题