1.maven引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
2.application.properties配置发送邮箱
//用户邮箱 spring.mail.username=753029781@qq.com //QQ邮箱开通第三方登录的授权码 spring.mail.password=xxxxxxxxxxxx //主机地址 spring.mail.host=smtp.qq.com //开启安全的连接 spring.mail.properties.mail.smtp.enable=true
3.测试
import cn.kgc.elastic.vo.Book; import org.junit.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.MimeMailMessage; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.test.context.junit4.SpringRunner; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.File; @RunWith(SpringRunner.class) @SpringBootTest public class SpringBoot03ApplicationTests { //注入邮件发送器 @Autowired JavaMailSenderImpl mailSender; @Test public void sentMail(){ //发送简单的邮件 SimpleMailMessage message=new SimpleMailMessage(); //邮件设置 //标题 message.setSubject("注意"); //内容 message.setText("有内鬼,终止交易"); //发送人 message.setFrom("753029781@qq.com"); //收件人 message.setTo("jumpjiang233@gmail.com"); mailSender.send(message); } @Test public void tesr01() throws MessagingException { //复杂邮件发送 MimeMessage mimeMessage=mailSender.createMimeMessage(); //使用helper上传文件 MimeMessageHelper helper=new MimeMessageHelper(mimeMessage,true); helper.setSubject("注意"); //可以HTML样式 helper.setText("<b style='color:blue'>有内鬼,终止交易</b>",true); //上传文件,可以上传多个 helper.addAttachment("1.jpg",new File("C:\\Users\\Jump\\Pictures\\1.jpg")); helper.setFrom("753029781@qq.com"); helper.setTo("2871382340@qq.com"); mailSender.send(mimeMessage); } @Test public void contextLoads() { } }