14-springboot系列: 邮件发送

隐身守侯 提交于 2020-12-18 03:17:19


      今天讲解springboot的spring-boot-starter-mail邮件发送,业务场景:注册验证,忘记密码或者是给用户发送营销信息等。


1、pom配置

    <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配置邮箱

#邮箱服务器地址spring.mail.host=smtp.163.com#用户名spring.mail.username=z13128600812@163.com#开通授权码spring.mail.password=**********spring.mail.default-encoding=UTF-8spring.mail.properties.mail.smtp.auth=truespring.mail.port=25
mail.fromMail.addr=z13128600812@163.com



3、发送邮件服务实现


@Componentpublic 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、测试类发送邮件

@RunWith(SpringRunner.class)@SpringBootTestpublic 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、运行结果

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'



源码获取:

关注公众号,输入"springboot-parent"获取git地址


历史回顾:

[20200405]  10-springboot系列:多数据源

[20200406]  11-springboot系列:Mybatis注解使用

[20200407] 12-springboot系列:Mybatis的xml使用

[20200607] 13-springboot系列:定时任务


作者微信号:13128600812

加入技术群讨论,备注:1

软件定制及其他业务,备注:2







本文分享自微信公众号 - IT技术屋(zhanglcxyworkshop)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!