1.添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.配置文件application.properties
qq邮箱配置
spring.mail.host=smtp.qq.com
spring.mail.username=xxxxxxx@qq.com
spring.mail.password=xxxxxxxx //这里填写qq的授权码
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
outlook邮箱配置
spring.mail.host=smtp.qiye.163.com
spring.mail.username=xxxxx@xxxxx.com
spring.mail.password=xxxxxxxxxxx
spring.mail.port=4xxxx
spring.mail.protocol=smtp
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.properties.mail.smtp.socketFactory.port=xxxx
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
3.测试函数
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
@Autowired
private JavaMailSender javaMailSender;
public String sendMail(){
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage ,true,"UTF-8");
try {
helper.setFrom("xxxxxxx@qq.com");
helper.setTo("xxxxxxxxx@qq.com");
helper.setSubject("标题:测试标题");
helper.setText("测试内容部份");
//添加附件
//FileSystemResource file = new FileSystemResource("d:\\file-online-preview.zip");//这里是双反斜杠
//helper.addAttachment(file.getFilename(), file);
javaMailSender.send(mimeMessage);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "success";
}
注:如果执行发送邮件报错
STARTTLS is required but host does not support STARTTLS
则把以下两个配置参数设置为false即可
spring.mail.properties.mail.smtp.starttls.enable=false
spring.mail.properties.mail.smtp.starttls.required=false