pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
application.properties
spring.mail.username=xxxx@qq.com
spring.mail.password=授权码
spring.mail.host=smtp.qq.com
#安全连接
spring.mail.properties.mail.smtp.enable=true
实例一:
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
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 org.springframework.test.context.junit4.SpringRunner;
import javax.mail.internet.MimeMessage;
import java.io.File;
@RunWith(SpringRunner.class)
@SpringBootTest
class DemoApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
//简单
@Test
public void contextLoads(){
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("学习");//主题
message.setText("Hello");//内容
message.setFrom("xxx@qq.com"); //哪里来
message.setTo("xxx@qq.com"); //那里去
mailSender.send(message); //发送邮件
}
//复杂
@Test
public void test2() throws Exception {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setSubject("Java"); //主题
helper.setText("<h1>Hello<h1>", true); //内容
//附件
helper.addAttachment( "1.jpg",new File("G:\\SpringBoot-mail\\src\\main\\static\\JDBC链接.png"));
helper.setFrom("xxx@qq.com"); //哪里来
helper.setTo("xxx@qq.com"); //那里去
mailSender.send(mimeMessage); //发送邮件
}
}
实例二:
@SpringBootTest
class Springboot09TaskApplicationTests {
@Autowired
private JavaMailSenderImpl mailSender;
/**
* 测试简单的邮件发送
*/
@Test
void contextLoads() {
SimpleMailMessage message = new SimpleMailMessage();
//邮箱主题
message.setSubject("这是一个简单邮箱的主题");
//邮箱内容
message.setText("这是一个简单邮箱的内容");
//收件人:发送给谁
message.setTo("LuZQ000@163.com");
//发件人:谁发送的
message.setFrom("LuZQ000@163.com");
//发送
mailSender.send(message);
}
/**
* 测试复杂的邮件发送
*/
@Test
void contextLoads1() throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
//设置为tue 支持多文件上传
MimeMessageHelper helper = new MimeMessageHelper(message,true);
//邮箱主题
helper.setSubject("这是一个复杂邮箱的主题");
//邮箱内容
//setText("内容",true) true表示可以解析html代码
helper.setText("<p style='color:red'>这是一个复杂邮箱的内容</p>",true);
//附件
helper.addAttachment("1.jpg",new File("F:\\1.jpg"));
helper.addAttachment("2.jpg",new File("F:\\1.jpg"));
//收件人:发送给谁
helper.setTo("LuZQ000@163.com");
//发件人:谁发送的
helper.setFrom("LuZQ000@163.com");
//发送邮件
mailSender.send(message);
}
}