首先登录Gmail账号
找到这个地方

然后查看所有配置

然后贴代码:
private static String from = "youAccount@gmail.com";//发送者的谷歌邮箱
private static String password = "password";//谷歌邮箱密码
public static boolean sendMailGMail(String to, String content) {
return gmailSender(from,password,to,"标题", content);
}
private static void gmailSsl(Properties props) {
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
props.put("mail.debug", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
props.put("mail.smtp.port", "465");
//props.put("mail.smtp.port", "587");
props.put("mail.smtp.socketFactory.port", "465");
//props.put("mail.smtp.socketFactory.port", "587");
props.put("mail.smtp.auth", "true");
}
public static boolean gmailSender(String from,String password,String email,String subject,String content) {
Properties props = new Properties();
gmailSsl(props);
Session session = Session.getDefaultInstance(props,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password);
}
});
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(email));
msg.setSubject(subject);
msg.setText(content);
msg.setSentDate(new Date());
Transport.send(msg);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
return true;
}
到此别以为就能发送了 哈哈哈 我也是这么认为,但是还发送不了 提示了
javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted
那这个时候就需要修改一下谷歌账号配置了:
登录到您发送邮件的 Gmail 帐户
转到管理您的 Google 帐户 -> 安全性 -> 不太安全的应用程序访问 -> 打开访问(不推荐)
或
访问 URL:https://www.google.com/settings/security/lesssecureapps
将“允许安全性较低的应用程序:关闭”改为“允许安全性较低的应用程序:开启”

至此,点击发送就能发送啦!!!!
踩坑不易,点个赞吧~
本文介绍了如何使用Java对接谷歌Gmail邮箱,以及遇到AuthenticationFailedException错误时的解决步骤,包括检查Gmail账号设置,允许不太安全的应用程序访问,以解决535-5.7.8错误。
2151

被折叠的 条评论
为什么被折叠?



