Java对接谷歌邮箱-代码及其谷歌邮箱账号配置

本文介绍了如何使用Java对接谷歌Gmail邮箱,以及遇到AuthenticationFailedException错误时的解决步骤,包括检查Gmail账号设置,允许不太安全的应用程序访问,以解决535-5.7.8错误。

首先登录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
将“允许安全性较低的应用程序:关闭”改为“允许安全性较低的应用程序:开启”

至此,点击发送就能发送啦!!!!

踩坑不易,点个赞吧~

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值