1、pom.xml添加 spring-boot-starter-mail 依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
2、application.properties中添加发送邮件的配置
spring.mail.host=smtp.163.com
spring.mail.port=25
spring.mail.username=发送邮件的账号@163.com
spring.mail.password=授权码
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
mail.fromMail.addr=发送邮件的账号@163.com
3、发送邮件的接口
package com.st.service;
public interface MailService {
public void sendSimpleMail(String to, String subject, String content);
}
4、发送邮件的实现类
package com.st.service.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.Component;
import org.springframework.stereotype.Service;
import com.st.service.MailService;
@Service
@Component
public class MailServiceImpl implements MailService {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private JavaMailSender mailSender;
@Value("${mail.fromMail.addr}")
private String from;
@Override
public void sendSimpleMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
try {
mailSender.send(message);
logger.info("发送成功。。。。。。");
} catch (Exception e) {
logger.error("发送失败!!!!!!", e);
}
}
}
5、测试类
package com.st;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.st.service.MailService;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootMailApplicationTests {
@Autowired
private MailService mailService;
//生成6位随机验证码
int randNum = 1 + (int)(Math.random() * ((999999 - 1) + 1));
@Test
public void testSimpleMail() throws Exception {
mailService.sendSimpleMail("接收邮件的账号@qq.com", "开发邮件发送功能", "验证码:"+randNum);
}
}