导入mail包
<!-- 导入邮件包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
text练习测试
package com.lu.springboottasks;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@SpringBootTest
class SpringbootTasksApplicationTests {
@Autowired
JavaMailSenderImpl javaMailSender;
@Test
void contextLoads() {
//一个简单的邮件
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setSubject("鲁家见你好啊");//设置标题
simpleMailMessage.setText("我是你未来的老婆我喜欢你");//文件内容
simpleMailMessage.setTo("482475181@qq.com");//发送给谁
simpleMailMessage.setFrom("482475181@qq.com");//接受发送过来的邮件
javaMailSender.send(simpleMailMessage);
}
@Test
void contextLoads2() throws MessagingException {
//一个复杂的邮件
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//组装
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
mimeMessageHelper.setSubject("鲁家见你好哦啊");
mimeMessageHelper.setText("<H1>我是你未来的老婆<H1>",true);
//附件
mimeMessageHelper.addAttachment("1.jpg",new File("D:\\background.jpg"));
mimeMessageHelper.addAttachment("2.jpg",new File("D:\\background.jpg"));
mimeMessageHelper.setTo("482475181@qq.com");//发送给谁
mimeMessageHelper.setFrom("482475181@qq.com");//接受发送过来的邮件
javaMailSender.send(mimeMessage);
}
//可以进行再次封装
}
还要在qq邮箱中设置
开启服务: