导包<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
结构是这样的
MailService接口
package com.zq.email.service;
public interface MailService {
/**
* 发送邮件
*
* @param to 邮件收件人
* @param subject 邮件主题
* @param verifyCode 邮件验证码
*/
void sendMail(String receive, String subject, String verifyCode);
}
MailService实现类
package com.zq.email.service.iml;
import com.zq.email.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
@Service
public class MailServiceIml implements MailService {
@Autowired
private JavaMailSender sender;
@Value("${mail.fromMail.addr}")
private String from;
/**
* @param receive 邮件收件人
* @param subject 邮件主题
* @param verifyCode 邮件验证码
*/
@Override
public void sendMail(String receive, String subject, String verifyCode){
SimpleMailMessage message = new SimpleMailMessage();
// 主题
message.setSubject(subject);
// 文本
message.setText("暗号是:" + verifyCode);
// 发件人
message.setFrom(from);
// 收件人
message.setTo(receive);
// 发送
sender.send(message);
}
}
MailController
package com.zq.email.controller;
import com.zq.email.service.iml.MailServiceIml;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/mail")
public class MailController {
@Autowired
private MailServiceIml mailSender;
@RequestMapping("/send")
public String mailSend() {
mailSender.sendMail("ovo.sk@qq.com", "请回暗号", "5201314");
return "发送成功";
}
}
- 效果图1
- 效果图2
启动项目:访问 http://localhost:8080/mail/send
- 效果图1
- 效果图2
源码地址:https://gitee.com/kk-dad/email/tree/main