SpringBoot1.5.12.RELEASE傳送郵件
阿新 • • 發佈:2018-12-04
SpringBoot1.5.12.RELEASE傳送郵件
首先 第一步 加入郵件的場景啟動器,也就是Maven座標
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
第二步 傳送郵件的賬號開啟POP3/IMAP服務
第三步 在application.properties配置檔案中加入如下配置
spring.mail.username=自己傳送郵件的賬號 spring.mail.password=jfubjpypbpjxebch spring.mail.host=smtp.qq.com spring.mail.properties.mail.smtp.ssl.enable=true
第四步 測試傳送郵件
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.MimeMessageHelper;
import org.springframework.test.context.junit4.SpringRunner;
import javax.mail.internet.MimeMessage;
import java.io.File;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Springboot04TaskApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
public void contextLoads() {
SimpleMailMessage message = new SimpleMailMessage();
//郵件設定
message.setSubject("通知-今晚開會");
message.setText("今晚7:30開會");
message.setTo(" [email protected]");
message.setFrom("[email protected]");
mailSender.send(message);
}
@Test
public void test02() throws Exception{
//1、建立一個複雜的訊息郵件
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
//郵件設定
helper.setSubject("通知-今晚開會");
helper.setText("<b style='color:red'>今天 7:30 開會</b>",true);
helper.setTo(" [email protected]");
helper.setFrom("[email protected]");
//上傳檔案
helper.addAttachment("1.jpg",new File("C:\\Users\\lfy\\Pictures\\Saved Pictures\\1.jpg"));
helper.addAttachment("2.jpg",new File("C:\\Users\\lfy\\Pictures\\Saved Pictures\\2.jpg"));
mailSender.send(mimeMessage);
}
}