本来是想整合阿里的短信服务到项目里面的,但是要付费,穷学生,舍不得花钱,就先使用邮件替代。
这里只先记录一下邮件发送简单的验证码文本,和发送带附件的文本,发送复杂文本,比如html页面那样添加样式什么的,后面有需要再加上来。
https://docs.spring.io/spring-boot/docs/current/reference/html/application-properties.html#application-properties.mail
上面是springboot官网的文档说明。
下面是整合步骤:
1.配置文件
spring.mail.host=smtp.qq.com
spring.mail.username=525252XX@qq.com
spring.mail.password=你的授权码
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
2.测试使用:
@SpringBootTest
class GulimallAuthServerApplicationTests {
@Autowired
JavaMailSender mailSender;
@Test
public void sendMimeMail( ) {
try {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setSubject("验证码邮件");//主题
String code = "546555";
mailMessage.setText("您的验证码是:"+code);//内容
mailMessage.setTo("218xxxxx@qq.com");//发给谁
mailMessage.setFrom("5152xxx@qq.com");//你自己的邮箱
System.out.println("发送成功!");
mailSender.send(mailMessage);//发送
}catch (Exception e){
e.printStackTrace();
}
}
//发送大文件/附件的邮件
@Test
public void sendBigEmail() {
String receiverName = "21835xxxx@qq.com";
String title = "带附件的邮件";
String content ="您的验证码是:";
File file = new File("C:\\Users\\PC\\Pictures\\Saved Pictures\\R-C.jpg");
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message,true);
helper.setFrom("51529xxx@qq.com");
helper.setTo(receiverName);
helper.setSubject(title);
helper.setText(content);
FileSystemResource resource = new FileSystemResource(file);
helper.addAttachment("附件", resource);
}catch (Exception e){
e.printStackTrace();
}
mailSender.send(message);
}
}
这样就完了。。。