参考:
http://www.ityouknow.com/springboot/2017/05/06/springboot-mail.html
- 发送邮件是网站必备功能之一,spring推出了 JavaMailSender 简化了邮件发送的过程,之后springboot对此进行了封装就有了现在的spring-boot-starter-mail,
- 首先添加依赖。在 pom.xml 中添加 spring-boot-starter-mail
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
</dependencies>
- 在 application.properties 中添加邮箱设置
spring.mail.host=smtp.qiye.163.com //邮箱服务器地址spring.mail.username=xxx@oo.com //用户名 发送方的邮箱
spring.mail.password=xxyyooo //密码 对于QQ邮箱,密码是发送方授权码
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=xxx@oo.com //以谁来发送邮件
- 编写mailService,这里只提出实现类。
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.编写test类测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class MailServiceTest {
@Autowired
private MailService MailService;
@Test
public void testSimpleMail() throws Exception {
MailService.sendSimpleMail("ityouknow@126.com","test simple mail"," hello this is simple mail");
}
}