1.pom.xml中配置依赖
2.application.properties填写配置项
3.服务曾service
4.controller层面
5.前端api写法
6.页面调用
1.pom.xml配置
-
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-mailartifactId>
-
2.application.properties
-
- spring.mail.username=14xxx82173@qq.com
- spring.mail.password=pxdblgfykzdeddiafh
- spring.mail.host=smtp.qq.com
- spring.mail.properties.smtp.ssl.enable=true
注意:不需要加引号;我这里使用的是QQ
3.service
- package com.spm.service;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.mail.javamail.JavaMailSender;
- import org.springframework.mail.javamail.MimeMessageHelper;
- import org.springframework.stereotype.Service;
-
- import javax.mail.MessagingException;
- import javax.mail.internet.MimeMessage;
-
- @Service
- public class EmailService {
-
- @Autowired
- private JavaMailSender javaMailSender;
-
- public void sendEmail(String to, String subject, String text) throws MessagingException {
- MimeMessage mimeMessage = javaMailSender.createMimeMessage();
- MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
-
- try {
- messageHelper.setFrom("1xxxx482173@qq.com");
- messageHelper.setTo(to);
- messageHelper.setSubject(subject);
- messageHelper.setText(text);
-
- javaMailSender.send(mimeMessage);
- } catch (MessagingException e) {
- e.printStackTrace();
- }
- }
- }
注意设置setFrom
4.controller层
- package com.spm.controller;
- import com.spm.service.EmailService;
- import com.spm.utils.AjaxResult;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.transaction.annotation.Transactional;
- import org.springframework.web.bind.annotation.*;
-
- import javax.mail.MessagingException;
-
- @RestController
- @RequestMapping("/api/email")
- @Transactional(rollbackFor = Exception.class)
- public class EmailController {
-
- @Autowired
- private EmailService emailService;
-
- @PostMapping("/send")
- public String sendEmail(@RequestParam String to, @RequestParam String subject, @RequestParam String text) throws MessagingException {
- emailService.sendEmail(to, subject, text);
- return "111";
- }
- }
5.前端api.js
- // 发邮件
- export function sendEmail(to, subject, text) {
- return request({
- url: '/dev/api/email/send',
- method: 'post',
- params: {
- to, subject, text
- }
- })
- }
6.前端调用
import { sendEmail } from '@/api/user'
senE() {
sendEmail('2895577104@qq.com', '标题', 'hello').then((res) => {
console.log('发送邮件测试结果', res)
})
}