先开启发送人邮箱的POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务,拿QQ邮箱来说明
登录->设置->(下滑)POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务->开启服务
获得授权码

import com.sun.mail.util.MailSSLSocketFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class MailUtil{
private static Logger logger = LoggerFactory.getLogger(MailUtil.class);
public static void send(String email, String userId , String code) {
String from = "[email protected]";
String host = "smtp.qq.com";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.auth", "true");
try {
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
Session session = Session.getDefaultInstance(properties, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]", "xkxnxxxxeljdga");
}
});
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
message.setSubject("账号**");
String content = "<html><head></head><body><h1>这是一封**邮件,**请点击以下链接</h1><h3>"
+ "<a href='http://localhost:8081/user/active?userId=" + userId + "&code=" + code
+ "'>http://localhost:8081/user/active?userId=" + userId + "&code=" + code
+ "</href></h3></body></html>";
message.setContent(content, "text/html;charset=UTF-8");
Transport.send(message);
logger.info("email send successfully");
} catch (Exception e) {
e.printStackTrace();
}
}
}