栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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

踩坑不易,点个赞吧~

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/355902.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号