2011-12-23 63 views
6

我想做一个可以发送电子邮件到任何指定收件人(gmail)的函数。我正面临的问题是当我尝试提供在gmail中使用双向身份验证的凭据时,我的身份验证失败。通过帐户没有双向身份验证,它工作正常。那么我需要做些什么来使事情发生在启用双向认证的情况下?通过双向认证的gmail帐户中的java发送电子邮件

以下是我用来发送电子邮件的代码。

public static boolean sendMail(String fromMail, String fromPassword, String toMail, String message) { 
     try { 
      final String user = fromMail, password = fromPassword; 
      Properties prop = new Properties(); 
      prop.setProperty("mail.smtp.host", "smtp.gmail.com"); 
      prop.setProperty("mail.smtp.port", "465"); 
      prop.setProperty("mail.smtp.auth", "true"); 
      prop.setProperty("mail.smtp.ssl.enable", "true"); 
//   prop.put("mail.debug", "true"); 

//   prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); 

      Session sess = Session.getDefaultInstance(prop, new Authenticator() { 

       @Override 
       protected javax.mail.PasswordAuthentication getPasswordAuthentication() { 
        return new javax.mail.PasswordAuthentication(user, password); 
       } 
      }); 

//   Session sess=Session.getDefaultInstance(prop); 

      sess.setDebug(true); 

      Message msg = new MimeMessage(sess); 

      msg.setFrom(new InternetAddress(fromMail)); 
      msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toMail)); 
      msg.setText(message); 
      msg.setContent(message, "text/html"); 


      Transport.send(msg); 
      return true; 
     } catch (MessagingException msgEx) { 
      msgEx.printStackTrace(); 
      return false; 
     } 
    } 

回答

5

通过在https://accounts.google.com/IssuedAuthSubTokens上创建应用专用密码。还请查看this youtube video关于应用程序特定的密码。

+0

我检查了链接并获得了一个特定于应用程序的密码,并且我能够成功登录到浏览器。但是在这里的代码中,我需要指定那个密码。因为它也生成应用程序特定的密码后仍然给我错误。 – ankurtr 2011-12-23 22:06:18

+0

有趣。前一段时间,当我遇到这种情况时,谷歌smtp服务给了我一个双向auth特定的错误信息。你碰巧检查过吗? – Friek 2011-12-23 22:16:56

+0

是的,我只是在说这个。我得到名为“javax.mail.AuthenticationFailedException:535-5.7.1需要应用程序特定的密码”的错误。那么该怎么做才能解决这个问题? – ankurtr 2011-12-23 22:19:17

2

这有两个解析:

  1. 您可以生成由给定链路的专用密码“friek”,即“https://accounts.google.com/IssuedAuthSubTokens”和使用生成应用程序专用密码的地方你的原始密码。我已经做到了这一点,其工作

  1. 为什么异常的原因(javax.mail.AuthenticationFailedException:535-5.7.1应用专用密码是必需的)发生的是,你可能有激活了您的gmail帐户的两步验证。如果您使用的帐户未启用两步验证,则可以通过原始密码发送电子邮件。我也试过这个,它的工作正常。
+0

你是对的,我刚刚创建了没有两步验证的新帐户,它对我来说工作顺利。感谢帮助 !! – Akash5288 2016-11-02 08:11:06

相关问题