此代码有什么问题?我正在尝试使用hMailServer在本地主机上发送电子邮件,但无法正常工作。虽然此代码适用于Gmail SMTP服务器。.我可能认为该错误出在我的hMailServer中,但我找不到它。

    try{
    String host = "127.0.0.1";
    String from = "[email protected]";
    String pass = "1q2w#E$R";
    Properties props = System.getProperties();
    props.put("mail.smtp.starttls.enable", "true"); // added this line
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.user", from);
    props.put("mail.smtp.password", pass);
    props.put("mail.smtp.port", "25");
    props.put("mail.smtp.auth", "true");

    String[] to = {"[email protected]"}; // added this line

    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));

    InternetAddress[] toAddress = new InternetAddress[to.length];

    // To get the array of addresses
    for( int i=0; i < to.length; i++ ) { // changed from a while loop
        toAddress[i] = new InternetAddress(to[i]);
    }
    for( int i=0; i < toAddress.length; i++) { // changed from a while loop
        message.addRecipient(Message.RecipientType.TO, toAddress[i]);
    }
    message.setSubject("sending in a group");
    message.setText("Welcome to JavaMail");
    Transport transport = session.getTransport("smtp");
    transport.connect(host, from, pass);
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }


这是我得到的错误:

    javax.mail.MessagingException: Could not connect to SMTP host: 127.0.0.1, port: 25;
nested exception is:
    java.net.SocketException: Permission denied: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1213)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:311)
    at javax.mail.Service.connect(Service.java:233)
    at javax.mail.Service.connect(Service.java:134)
    at nl.company.cms.login.emailservice.TestMail.main(TestMail.java:71)


我正在使用hMailServer。

最佳答案

如果您使用的是Java 7,那么我将在启动应用程序时尝试将其添加为JVM参数:

-Djava.net.preferIPv4Stack=true

这可能是必要的,因为Java现在正在尝试使用IPv6,因此我们需要告诉它更喜欢IPv4堆栈。

07-25 21:29