springboot-mail

  配置springboot发送简易右键

maven依赖

1
2
3
4
5
6
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
</dependencies>

编写service以及实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//Service
public interface MailService {
void sendSimpleMail(String to, String subject, String content);
}
//ServiceImpl
@Component
@Log
public class MailServiceImpl implements MailService {
@Resource
private JavaMailSender javaMailSender;

@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 {
javaMailSender.send(message);
log.info("简单邮件已经发送。");
} catch (Exception e) {
log.info("发送简单邮件时发生异常!"+e);
}
}
}

配置必要属性设置

1
2
3
4
5
6
7
8
9
spring:
mail:
host: smtp.qq.com
username: xzx@qq.com
default-encoding: UTF-8
password: password
mail:
fromMail:
addr: xzx@qq.com

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = WebsiteApplication.class)
@WebAppConfiguration
public class MailServiceTest {

@Resource
private MailService mailServiceImpl;

@Test
public void testSimpleMail() throws Exception {
mailServiceImpl.sendSimpleMail("mir2285@outlook.com", "test simple mail", " hello this is simple mail");
}
}