SpringBoot-JavaMail ----傳輸郵件
阿新 • • 發佈:2018-11-25
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
/dependency>
spring: mail: username: [email protected] password: 郵箱校驗碼 host: smtp.qq.com properties: mail: smtp: ssl: enable: true
package com.shi.snyc;
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 SnycApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
public void contextLoads() {
//簡單格式傳輸郵件
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("設定標題");
message.setText("設定內容");
message.setTo(" [email protected]");
message.setFrom("[email protected]");
mailSender.send(message);
}
@Test
public void test2() throws Exception{
//建立一個複雜的訊息郵件
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
helper.setSubject("設定標題");
helper.setText("<b style='color:red'>設定內容</b>",true);//使用html
helper.setTo(" [email protected]");
helper.setFrom("[email protected]");
helper.addAttachment("1.jpg",new File("C:\\Users\\low\\Desktop\\1.png"));
mailSender.send(mimeMessage);
}
}