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)@SpringBootTestpublic 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() { }}