代码示例
1.pom引入坐标
<!-- javamail -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2,application配置
spring:
mail:
host: smtp.qq.com
username: 318***986@qq.com
password: bdfy****jubjfe
3.service
package com.learning.service.impl;
import com.learning.service.SendMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
@Service
public class SendMailServiceImpl implements SendMailService {
@Autowired
private JavaMailSender javaMailSender;
@Override
public void sendMail() {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setFrom("318***986@163.com");
mailMessage.setTo("188****3780@163.com");
mailMessage.setSubject("测试主题");
mailMessage.setText("测试内容");
javaMailSender.send(mailMessage);
}
@Override
public void sendMimeMessage() {
MimeMessage mailMessage = javaMailSender.createMimeMessage();
try{
MimeMessageHelper helper = new MimeMessageHelper(mailMessage, true);
helper.setFrom("318***986@163.com");
helper.setTo("188****3780@163.com");
helper.setSubject("测试主题");
helper.setText("<font style='color:red'>测试内容</font>", true);
File f1 = new File("/opt/测试.txt");
File f2 = new File("D:\\test.png");
helper.addAttachment(f1.getName(), f1);
helper.addAttachment("测试.png", f2);
javaMailSender.send(mailMessage);
}catch(Exception e){
e.printStackTrace();
}
}
}