springboot-email 邮件发送实战

邮件发送是项目中经常要用到的功能,我们快速的学习和使用它。
准备工作:
(这里用QQ账号来做测试)

1.开启smtp服务

进入qq邮件后,点击账户,然后点击开启smtp服务,按照步骤开启完成
这里写图片描述]![(http://mmbiz.qpic.cn/mmbiz_png/sG1icpcmhbiaAq9X4lgcjdWF42NjoLVhYHD3RWeDkCLANicTzA7ZPlqrmjncHpuA34E5icibWgxiawmDD5v6Zp7TiaetQ/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1)

2.开发环境

  • jdk7
  • eclipse

使用eclipse创建简单的maven项目,引入springboot配置
这里写图片描述

项目包结构如下:

这里写图片描述

配置文件

server.port=8080
server.context-path=/email
spring.mail.debug=true
spring.mail.host=smtp.qq.com
spring.mail.username=492782442@qq.com
spring.mail.password=your auth code
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

spring.mail.password 密码qq对应得是授权码,如下图获取
这里写图片描述

核心代码

public String  sendSimpleMail() throws Exception {
 try {
        SimpleMailMessage message = new SimpleMailMessage();
         message.setFrom("[email protected]");
         message.setTo("[email protected]");
         message.setSubject("主题:励志程序员");
         message.setText("一分钟掌握邮件发送");
         mailSender.send(message);
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    logger.error("发送失败:" + e.getMessage());
    return "send error:" + e.getMessage();
}
    return "send success";       
 }

收信结果:
这里写图片描述

献上git地址, https://github.com/1497187976/springboot-email.git
不会使用github的移步
人人都要会的github从入门到实战

猜你喜欢

转载自blog.csdn.net/lzp492782442/article/details/78367562