这里以qq邮箱发送为例
步骤:
1、首先开通qq邮箱smtp服务
qq邮箱首页,设置-->账户-->点击:POP3/SMTP服务和IMAP/SMTP服务后面的【开启】按钮-->提示【短信验证】-->按要求编辑内容发送到指定的号码-->点击【我已发送】-->提示成功开启【SMTP和POP3】授权码就是在第三方登录的QQ邮箱密码。
2、搭建springboot项目
pom.xml中引入:
<!-- email -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
yml文件配置:
#邮件发送配置
spring:
mail:
host: smtp.qq.com
username: 982084398@qq.com
password: 开通smtp服务所生成的授权码
default-encoding: utf-8
properties:
main:
smtp:
auth: true
starttls:
enable: true
required: true
controller代码片段:
@Autowired
private JavaMailSender mailSender; //自动注入的Bean
@Value("${spring.mail.username}")
private String sender; //读取配置文件中的参数
/**
* 邮件发送功能
* @param
* @param
* @return
*/
@RequestMapping("/api/email")
@ApiOperation(value = "用户发送邮件操作", httpMethod = "GET", response = String.class, notes = "用户发送邮件操作,提供用户管理-用户发送邮件操作")
public String sendEmail(HttpServletRequest request) {
logger.info("email:"+sender );
MimeMessage message = null;
try {
message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
/**发送者邮箱,即为开通了smtp服务的邮箱*/
helper.setFrom(sender);
/**发送到的邮箱*/
helper.setTo(sender);
helper.setSubject("主题:带附件的邮件");
helper.setText("带附件的邮件内容");
String rscId = "picture";
helper.setText("<html><body>带静态资源的邮件内容 图片:<img src='cid:picture' style = 'width:600px;height:300px'/></body></html>", true);
//注意项目路径问题,自动补用项目路径
FileSystemResource file = new FileSystemResource(new File("E:\\aaaProjrct\\springboot\\picture.jpg"));
//加入邮件内容的图片
helper.addInline(rscId, file);
/**附件图片*/
helper.addAttachment("beautiful girl.jpg", file);
} catch (Exception e){
e.printStackTrace();
}
mailSender.send(message);
return "login";
}
3启动项目测试
请求:地址http://localhost:8087/api/email
qq邮箱会收到一封自己发给自己的邮箱。