在 netbeans 错误中使用 javamail

Using javamail in netbeans error

我尝试在 Netbeans 中使用 javamail 函数,但一直收到错误

javax.mail.MessagingException: Could not connect to SMTP host: 10.101.3.229,  port: 25;
nested exception is:
java.net.ConnectException: Connection timed out: connect

我使用的代码是:

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class TESTINGemail {

public static void main(String [] args)
{    
  String to = "abcd@gmail.com";
  String from = "web@gmail.com";

  String host = "localhost";

  Properties properties = System.getProperties();

  properties.setProperty("mail.smtp.host", host);

  Session session = Session.getDefaultInstance(properties);

  try{
     MimeMessage message = new MimeMessage(session);

     message.setFrom(new InternetAddress(from));

     message.addRecipient(Message.RecipientType.TO,
                              new InternetAddress(to));

     message.setSubject("This is the Subject Line!");

     message.setText("This is actual message");

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

我使用了一个教程,这基本上就是他们使用的代码。我曾尝试更改主机但每次都失败了。

如果您使用 gmail id 发送邮件,则不能使用 localhost 您必须使用 gmail 主机服务器地址 'mail.smtp.host' 所以您试试这个。

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class MailSender {
  public static void send (String to,String message1,String subject,String ss)
      throws Exception {
    String host ="smtp.gmail.com";
    String from="from@gmail.com";
    String password="Your password";
    Properties props = System.getProperties();

  props.put("mail.transport.protocol", "smtps");
  props.put("mail.smtp.user", from);
  props.put("mail.smtp.password", password);
  props.put("mail.smtp.port", "465");
  props.put("mail.smtps.auth", "true");
  props.put("mail.smtp.starttls.enable","true");

    props.put("mail.smtp.host", host);

    Session session = Session.getInstance(props, null);


    MimeMessage message = new MimeMessage(session);
    message.setFrom( new InternetAddress(from));
    message.addRecipient( Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);
    message.setText(message1);



    Transport transport = session.getTransport("smtps");
    transport.connect(host,from, password);
    transport.sendMessage(message, message.getAllRecipients());
    System.out.println("mail has been sent");
}


  public static void main(String arg[]) throws Exception
  {

      MailSender m=new MailSender();
      m.send("to@gmail.com", "hello ..", "test mail...","");
  }
  }

并禁用您的 PC 防病毒软件和防火墙,并在 google 帐户设置中打开 'Access for less secure apps'。

https://www.google.com/settings/security/lesssecureapps.