开启邮箱pop
开启两步验证
获取Google应用专用密码
URL
添加JavaMail库的依赖
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
代码(需要代理)
package com.bird.utils.googleUtil;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Date;
import java.util.Properties;
public class GoogleSendEmailUtil {
/**
*
* @param email 收件人电子邮件地址
* @param subject 邮件主题
* @param content 邮件内容
* @return
*/
public static Boolean sendEmail(String email, String subject, String content) {
// 使用Gmail发送邮件的SMTP服务器
String host = "smtp.gmail.com";
// Gmail账号或发件人电子邮件地址
final String username = "******";
// Gmail密码(如果使用两步验证,需要使用应用专用密码)
final String password = "*******";
//gmail邮箱的TLS方式
// 设置系统属性
Properties properties = System.getProperties();
// 设置邮件服务器
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
// 获取默认的Session对象
Session session = Session.getInstance(properties, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// 创建默认的MimeMessage对象
MimeMessage message = new MimeMessage(session);
// 设置发件人
message.setFrom(new InternetAddress(username));
// 设置收件人
message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
// 设置邮件主题
message.setSubject(subject,"UTF-8");
// 设置邮件内容
MimeBodyPart text = new MimeBodyPart();
text.setContent(content,"text/html;charset=UTF-8");
MimeMultipart mimeMultipart = new MimeMultipart();
mimeMultipart.addBodyPart(text);
mimeMultipart.setSubType("related");
message.setContent(mimeMultipart);
//设置邮件的发送时间,默认立即发送
message.setSentDate(new Date());
// 发送消息
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (Exception mex) {
mex.printStackTrace();
}
return true;
}
/*
* gmail邮箱SSL方式
*/
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.socketFactory.port", "465");
props.put("mail.smtp.auth", "true");
}
}
附上IDEA设置代理