
今天讲解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=25mail.fromMail.addr=z13128600812@163.com
3、发送邮件服务实现
public class MailServiceImpl implements MailService {private final Logger logger = LoggerFactory.getLogger(this.getClass());private JavaMailSender mailSender;private String from;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、测试类发送邮件
public class MailServiceTest {private MailService MailService;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地址
历史回顾:
[20200407] 12-springboot系列:Mybatis的xml使用
[20200607] 13-springboot系列:定时任务
作者微信号:13128600812
加入技术群讨论,备注:1
软件定制及其他业务,备注:2


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