我想做一个可以发送电子邮件到任何指定收件人(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;
}
}
我检查了链接并获得了一个特定于应用程序的密码,并且我能够成功登录到浏览器。但是在这里的代码中,我需要指定那个密码。因为它也生成应用程序特定的密码后仍然给我错误。 – ankurtr 2011-12-23 22:06:18
有趣。前一段时间,当我遇到这种情况时,谷歌smtp服务给了我一个双向auth特定的错误信息。你碰巧检查过吗? – Friek 2011-12-23 22:16:56
是的,我只是在说这个。我得到名为“javax.mail.AuthenticationFailedException:535-5.7.1需要应用程序特定的密码”的错误。那么该怎么做才能解决这个问题? – ankurtr 2011-12-23 22:19:17