在具有两种身份验证的gmail帐户中通过java发送电子邮件
我想制作一个可以向任何指定收件人(gmail)发送电子邮件的功能.我面临的问题是,当我尝试提供在 gmail 中使用两种身份验证的凭据时,我的身份验证失败.使用没有双向身份验证的帐户,它可以正常工作.那么在启用两种身份验证的情况下,我必须做些什么才能使事情发生呢?
I want to make a function which can send email to any specified recipient(gmail). The problem I am facing is my authentication fails when I try to provide credentials which uses two way authentication in gmail. With account having no two way authentication it works fine. So what I have to do to make things happen with two way authentications enabled?
以下是我用来发送电子邮件的代码.
Following is the code which I am using to send email.
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;
}
}
推荐答案
通过在 https:///accounts.google.com/IssuedAuthSubTokens.另请查看此 youtube 视频,了解应用程序特定密码.
By creating an application specific password at https://accounts.google.com/IssuedAuthSubTokens. Also check out this youtube video on application specific passwords.
相关文章