最近在项目中需要做一个邮件服务的功能,相信发送邮件也是很多项目中都需要具备的功能,由于我们项目是springboot加上是以maven来管理项目所以这篇文章就来实现一下springboot中的邮件发送功能,并记录自己烦的一些小错误。
1、在pom文件中添加spring-boot-starter-mail包的引用,代码如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2、在application.propertites文件中添加邮件相关配置:
spring.application.name=spirng-boot-mail
spring.mail.host=smtp.163.com //邮箱的服务地址,根据自己的邮箱可自行查看
spring.mail.username=*****@163.com //自己的邮箱地址
spring.mail.password=ASDFGHJ //客户端授权码
spring.mail.protocol=smtp
spring.mail.default-encoding=UTF-8
spring.mail.from=*****@163.com //与上述邮箱一样
在添加配置时需要注意想要项目给自己邮箱发邮件需要开启POP3/SMTP服务,开启时会发送一个客户端授权码,而配置时 spring.mail.password 需要的就是这个客户端授权码而不是自己的邮箱密码
3、接下来编写接口和实现类:
public interface MailService {
void sendMail(String to, String subject, String content);
}
@Component
public class MailServiceImpl implements MailService{
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.from}")
private String from;
@Override
public void sendMail(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);
}
}
}
4、编写单元测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class MailTest {
@Autowired
private MailService mailService;
@Test
public void testMail() throws Exception {
mailService.sendMail("******@163.com", "test mail", "hello this is Mail");
}
}
5、就可以去自己的邮箱查收邮件啦
邮件服务也可以发送不同类型邮件,例如带附件的邮件、带图片的邮件等