一、导入maven依赖
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
二、创建邮件工具类
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
public class EmailUtils {
private static String host = "smtp.163.com";
private static String username = "*****@163.com";
private static String password = "*****";
private static String protocol = "smtp";
private static boolean debug = true;
private EmailUtils(){}
public static void sendEmail(String to, String code) throws MessagingException, UnsupportedEncodingException {
//连接邮件服务器的参数设置
Properties properties = new Properties();
//设置服务器地址
properties.setProperty("mail.smtp.host",host);
//设置用户认证方式
properties.setProperty("mail.smtp.auth","true");
//设置传输协议
properties.setProperty("mail.transport.protocol", protocol);
//创建连接对象,连接到邮箱服务器
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}