上一篇:SpringBoot如何整合JPA-Hibernate? | 带你读《SpringBoot实战教程》之二十四
下一篇:如何实现发送带附件的邮件? | 带你读《SpringBoot实战教程》之二十六
本文来自于千锋教育在阿里云开发者社区学习中心上线课程《SpringBoot实战教程》,主讲人杨红艳,点击查看视频内容。
SpringBoot整合Email
添加依赖:
<!-- 邮件依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
创建全局配置文件:application.properties
# JavaMailSender 邮件发送的配置
spring.mail.host=smtp.qq.com #smtp.163.com
spring.mail.username=465008297@qq.com
spring.mail.password=cjmegwewmbiqcach #授权码
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
#若使用QQ邮箱发送邮件,则需要修改为spring.mail.host=smtp.qq.com,同时spring.mail.password改为QQ邮箱的授权码。
#QQ邮箱->设置->账户->POP3/SMTP服务:开启服务后会获得QQ的授权码
出现认证失败的解决方案:因为JDK1.8中jrelibsecurity中两个 jar 包替换的缘故。将下载后的local_policy.jar和US_export_policy.jar替换到JDK1.8的jrelibsecurity文件夹即可。
新建包:com.qianfeng.email
获取发件人的邮箱:
@Component
public class EmailConfig {
@Value("${spring.mail.username}")
private String emailFrom;
public String getEmailFrom() {
return emailFrom;
}
public void setEmailFrom(String emailFrom) {
this.emailFrom = emailFrom;
}
}
EmailService:
public interface EmailService {
//发送简单的邮件
void sendSimpleMail(String sendTo, String title, String content);
}
EmailServiceImpl:
@Service
public class EmailServiceImpl implements EmailService {
@Autowired
private EmailConfig emailConfig;
@Autowired
private JavaMailSender mailSender;
@Override
public void sendSimpleMail(String sendTo, String title, String content) {
//简单邮件的发送
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(emailConfig.getEmailFrom());
message.setTo(sendTo);
message.setSubject(title);
message.setText(content);
mailSender.send(message);
}
}
EmailController:
@Controller
public class EmailController {
@Autowired
private EmailService emailService;
@RequestMapping("/simple")
@ResponseBody
public String sendSimpleEmail() {
emailService.sendSimpleMail("465008297@qq.com", "你好", "明天去你家玩儿");
return "success";
}
}
在启动类中添加所有需要扫描的包:
@SpringBootApplication(scanBasePackages="com.qianfeng.email")
执行结果: