使用Java通过Gmail发送的问题

使用Java通过Gmail发送的问题,java,email,authentication,gmail,Java,Email,Authentication,Gmail,我有一个看起来非常简单的代码,可以尝试使用我的Gmail帐户从我的Java应用程序发送电子邮件。当我运行它时,它会崩溃,出现异常javax.mail.AuthenticationFailedException。代码如下: // Recipient's email ID needs to be mentioned. String to = "fredxya@gmail.com"; // Sender's email ID needs to be mentioned

我有一个看起来非常简单的代码,可以尝试使用我的Gmail帐户从我的Java应用程序发送电子邮件。当我运行它时,它会崩溃,出现异常
javax.mail.AuthenticationFailedException
。代码如下:

    // Recipient's email ID needs to be mentioned.
    String to = "fredxya@gmail.com";

    // Sender's email ID needs to be mentioned
    String from = "johnxyzn@gmail.com";

    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class",
            "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    Session session = Session.getDefaultInstance(props,
        new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("fredxyz@gmail.com","password");
            }
        });

    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("Test Subject");

        // Now set the actual message
        message.setText("this is a test");

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

我能够使用gmail使用TLS发送消息,具有以下属性:

props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");

也许它会对你们有用。

问题是我在Gmail中使用了两步验证。解决方案是使用特定于应用程序的密码(ASP):