首先添加邮箱依赖
<!--邮箱依赖-->
<dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.2</version> </dependency>
创建邮箱工具类
public class MailUtil { protected static String SmtpHost = "smtp.163.com";//所使用的邮箱 protected static String FromMail = "meng3097861290@163.com"; protected static String MailUserName = "meng3097861290@163.com"; protected static String MailUserPwd = "LLRYPRNHDZFFCENA";//邮箱授权密码 protected static String SmtpPort = "465";//设置初始密码,可以不赋值 public static void sendText(String to, String subject, String content){ Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", SmtpHost); props.put("mail.smtp.socketFactory.port", SmtpPort); // Get the Session object Session session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(MailUserName, MailUserPwd); } }); try { // Create a default MimeMessage object Message message = new MimeMessage(session); message.setFrom(new InternetAddress(FromMail)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // Set Subject message.setSubject(subject); // Put the content of your message message.setText(content); // Send message Transport.send(message); } catch (MessagingException e) { throw new RuntimeException(e); } } }
controller层
mapper、service层照旧更改密码数据库信息
注:测试时必须联网,否则后台报错