1创建Spring Boot项目
2导入依赖
3配置application.yml
spring: mail: host: # 邮箱服务器 例:smtp.qq.com username: ****@qq.com password: **** properties: mail: smtp: auth: true starttls: enable: true required: true
4MailService.java
package com.zhangz1.maildemo.service;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.mail.javamail.MimeMessageHelper;import org.springframework.stereotype.Service;import javax.annotation.Resource;import javax.mail.MessagingException;import javax.mail.internet.MimeMessage;@Servicepublic class MailService { @Resource JavaMailSender mailSender; private final Logger logger = LoggerFactory.getLogger(MailService.class); public String send(String sender, String receiver, String title, String text) { try { //建立邮件消息 MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); //发送方 helper.setFrom(sender); //接收方 helper.setTo(receiver); //发送的标题 helper.setSubject(title); //发送的内容 helper.setText(text); mailSender.send(message); } catch (MessagingException e) { logger.error(e.getMessage()); } return "发送成功"; }}
5MailController.java
package com.zhangz1.maildemo.controller;import com.zhangz1.maildemo.service.MailService;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;import java.util.Random;@RestControllerpublic class MailController { @Resource private MailService mailService; @RequestMapping("/sendMail") public String send() { String checkCode = String.valueOf(new Random().nextInt(899999) + 100000); String sender = "2659445660@qq.com"; //发送方邮箱 String receiver = "admin@zhangz1.top"; //接收方邮箱 String title = "验证码"; String text = "您的验证码为" + checkCode; return mailService.send(sender, receiver, title, text); }}
6测试
Spring框架中Java邮件支持的接口和类组织如下: