Sending email through java in gmail account having two way authentication(在具有两种身份验证的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.
这篇关于在具有两种身份验证的gmail帐户中通过java发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在具有两种身份验证的gmail帐户中通过java发送电子邮件


基础教程推荐
- 如何对 HashSet 进行排序? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01