邮件任务
1.导包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.配置
spring.mail.username=2545644870@qq.com
spring.mail.password=gmxawscfvzvoecjc
spring.mail.host=smtp.qq.com
#开启加密验证
spring.mail.properties.mail.smtp.ssl.enable=true
3.编写测试
package com.tian.spring09test;
import org.junit.jupiter.api.Test;
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 javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@SpringBootTest
class Spring09TestApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
// 简单的邮件
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("小狂神你好呀~");
message.setText("谢谢你的狂神说java系列课程");
message.setTo("2545644870@qq.com");
message.setFrom("2545644870@qq.com");
mailSender.send(message);
}
@Test
void contextLoads2() throws MessagingException {
// 复杂的邮件
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setSubject("小狂神你好呀~ PLUS");
helper.setText("<p style='color:red'></p>",true);
//附件
helper.addAttachment("1.png",new File("C:\\Users\\86159\\Desktop\\1.png"));
helper.addAttachment("2.png",new File("C:\\Users\\86159\\Desktop\\1.png"));
helper.setTo("2545644870@qq.com");
helper.setFrom("2545644870@qq.com");
mailSender.send(mimeMessage);
}
//封装成一个方法
/**
*
* @param html: 是否开启识别html
* @param subject :主题
* @param text:正文
* @throws MessagingException
* @Author tian
*/
public void sendEmail(Boolean html,String subject,String text) throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setSubject(subject);
helper.setText(text,html);
//附件
helper.addAttachment("1.png",new File("C:\\Users\\86159\\Desktop\\1.png"));
helper.addAttachment("2.png",new File("C:\\Users\\86159\\Desktop\\1.png"));
helper.setTo("2545644870@qq.com");
helper.setFrom("2545644870@qq.com");
mailSender.send(mimeMessage);
}
}