一、简单的纯文本邮件
pom文件
pom文件要添加与邮箱有关的依赖,这个springboot官方已经帮我们做好了,可以直接用,不用找第三方依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
SendEmailService
@Service
public class SendEmailService {
@Autowired
private JavaMailSenderImpl mailSender;
@Value("${spring.mail.username}")
private String from;
public void sendSimpleEmail(String to,String subject,String text){
SimpleMailMessage message=new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(text);
try{
mailSender.send(message);
System.out.println("纯文本邮件发送成功");
}catch (MailException e){
System.out.println("纯文本邮件发送失败"+e.getMessage());
e.printStackTrace();
}
}
}
yaml文件
spring:
mail:
host: smtp.qq.com
port: 587
username: 你的邮箱账号(比如QQ邮箱:XXXXX@qq.com)
password: 这个不一定是密码,QQ邮箱好像是要绑定手机号,给一个手机发个信息得到的,具体的大家可以去搜索了解一下
default-encoding: UTF-8
测试类编写测试函数
在这里我设置的主题名为纯文本测试,发送的内容是青青子衿,悠悠我心。但为君故,沉吟至今。
写到此处,笔者不禁感概,曹孟德的诗很有感染力,在此处,虽是抒发曹孟德对人才的渴望。但是现在很多人喜欢用这两句来表达爱意,我也一样。虽然作为一名理工男,很难懂得如何去爱一个女孩,但是我一直在准备,一直在锻炼自我,希望有一天我也可以遇到我的"青青子衿",为了她,我沉吟至今。
@SpringBootTest
class Springboot0119ApplicationTests {
@Autowired
private SendEmailService sendEmailService;
@Autowired
private TemplateEngine templateEngine;
@Test
public void sendSimpleMailTest() {
String to = "你的QQ邮箱";
String subject = "纯文本文件测试";
String text = "青青子衿,悠悠我心。但为君故,沉吟至今。";
sendEmailService.sendSimpleEmail(to, subject, text);
}
收到邮箱
二、发送有图片和附件的复杂邮件
SendEmailService
public void sendComplexEmail(String to, String subject, String text, String filePath, String rscId, String rscPath) {
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text, true);
FileSystemResource res = new FileSystemResource(new File(rscPath));
helper.addInline(rscId, res);
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
helper.addAttachment(fileName, file);
mailSender.send(message);
System.out.println("复杂邮件发送成功");
} catch (javax.mail.MessagingException e) {
System.out.println("复杂邮件发送失败 " + e.getMessage());
e.printStackTrace();
}
}
测试类
@Test
public void sendComplexEmailTest() {
String to="你的QQ邮箱";
String subject="图片";
StringBuilder text = new StringBuilder();
text.append("<html><head></head>");
text.append("<body><h3>魏晋风度指的是魏晋时期名士们所具有的那种率直任诞、清俊通脱的行为风格。饮酒、服药、清谈和纵情山水是魏晋时期名士所普遍崇尚的生活方式。一部《世说新语》可以说是魏晋风度的集中记录。</h3>");
String rscId = "img001";
text.append("<img src='cid:" +rscId+"'/></body>");
text.append("</html>");
String rscPath="D:\\大二上\\SpringBoot\\springboot01_19\\src\\main\\resources\\static\\images\\魏晋.webp";
String filePath="D:\\大二上\\SpringBoot\\springboot01_19\\src\\main\\resources\\application.yaml";
sendEmailService.sendComplexEmail(to,subject,text.toString(),filePath,rscId,rscPath);
}
发送复杂邮件测试