springboot系列12: 邮件发送
今天讲解springboot的spring-boot-starter-mail邮件发送,业务场景:注册验证,忘记密码或者是给用户发送营销信息等。
1、pom配置
1 2 3 4 5 6 7 8 9 10 | <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> </dependencies> |
2、application.propertis配置邮箱
1 2 3 4 5 6 7 8 9 10 11 | #邮箱服务器地址 spring.mail.host=smtp. 163 .com #用户名 spring.mail.username=z13128600812 @163 .com #开通授权码 spring.mail.password=********** spring.mail. default -encoding=UTF- 8 spring.mail.properties.mail.smtp.auth= true spring.mail.port= 25 mail.fromMail.addr=z13128600812 @163 .com |
3、发送邮件服务实现
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 | @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); } } } |
4、测试类发送邮件
1 2 3 4 5 6 7 8 9 10 11 12 | @RunWith (SpringRunner. class ) @SpringBootTest public class MailServiceTest { @Autowired private MailService MailService; @Test public void testSimpleMail() throws Exception { MailService.sendSimpleMail( "1796969389@qq.com" , "test simple mail" , " hello this is simple mail" ); } } |
5、运行结果
1 2 3 | 2020 - 06 - 07 23 : 02 : 00.365 INFO 5592 --- [ main] com.example.service.MailServiceTest : Started MailServiceTest in 2.461 seconds (JVM running for 7.097 ) 2020 - 06 - 07 23 : 02 : 01.618 INFO 5592 --- [ main] c.example.service.impl.MailServiceImpl : 简单邮件已经发送。 Disconnected from the target VM, address: '127.0.0.1:15328' , transport: 'socket' |
分类:
spring boot
标签:
spring
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?