Java发送邮件工具类
引入依赖
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
引入工具类
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class EmailUtils implements Runnable {
private String email;
private String emailKey;
public EmailUtils(String email,String emailKey) {
this.email = email;
this.emailKey = emailKey;
}
@Override
public void run() {
String from = "1551483075@qq.com";
String host = "smtp.qq.com";
Properties 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("1551483075@qq.com", "XXX");
}
});
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>激活码(10分钟内有效):"+emailKey+"</h3></body></html>";
message.setContent(content, "text/html;charset=UTF-8");
Transport.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
EmailUtils utils = new EmailUtils("1551483075@qq.com",889654);
utils.run();
}
}
使用场景
- 登录&注册接口中可以发送验证码验证
- 邮箱正确性验证
- 找回密码发送验证码
- 邮箱消息推送
- 发送其他链接等