Springboot+邮件任务

Springboot+异步任务简单入门

    • 1.介绍
      • qq邮箱配置
      • 依赖
      • application.properties
      • 测试方法

1.介绍

• 邮件发送需要引入spring-boot-starter-mail
• Spring Boot 自动配置MailSenderAutoConfiguration
• 定义MailProperties内容,配置在application.yml中 • 自动装配JavaMailSender
• 测试邮件发送

qq邮箱配置

Springboot+邮件任务_第1张图片

注意生成授权码一会儿需要用到

依赖

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-mail</artifactId>
		</dependency>

application.properties

spring.mail.username=1821184005@qq.com
#password填生成的授权码
spring.mail.password=cubwuwbuyqsnbbhh
#填SMTP地址qq的话就我这个就可以
spring.mail.host=smtp.qq.com
#开启安全连接
spring.mail.properties.mail.smtp.ssl.enable=true

测试方法

package com.atguigu.task;

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 test(){
	//简单邮件
		SimpleMailMessage message = new SimpleMailMessage();
		//邮件设置
		message.setSubject("通知-今晚开会");
		message.setText("今晚8点开会");

		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("今天 7:30 开会",true);

		helper.setTo("[email protected]");
		helper.setFrom("[email protected]");

		//上传文件
		helper.addAttachment("www.jpg",new File("C:\\Users\\18586\\Desktop\\www.jpg"));

		mailSender.send(mimeMessage);

	}

}

你可能感兴趣的:(spring,boot)