项目中,经常会有发送邮件的业务需求,本篇就以smtp为例,说明下使用中需要注意的问题.
1.首先,项目中引入依赖,编辑pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/>
</parent>
<java.version>1.8</java.version>
<!--发送邮件-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.然后,修改application.properties配置,这里注意区分开发,生产等环境
#邮件发送配置
spring.mail.host=smtp.qq.com
spring.mail.username=账号
spring.mail.password=授权码
spring.mail.protocol=smtp
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.port=465
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.default-encoding=UTF-8
spring.mail.from=账号
这里需要注意几个细节问题:
1)授权码,需要自行获取和设置
2).端口号,这里开启了ssl
3).空格和拼写错误问题,检查确认账号配置
3.编写邮件发送代码,示例如下:
@Component
public class EmailServiceImpl implements EmailService {
@Value("${spring.mail.from}")
private String email = "";
@Autowired
private JavaMailSender mailSender;
@Override
public SimpleMailMessage sendSimpleMessage(String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(email);
message.setTo(to);
message.setSubject(subject);
message.setText(text);
mailSender.send(message);
return message;
}
}
网友评论