springboot使用邮箱发消息

1.在pom.xml放入一下代码↓↓

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

2.在application.properties配置mail

#qq邮箱  只使用了qq邮箱
spring.mail.host=smtp.qq.com
#想要发送邮箱的一方
spring.mail.username=12580007@qq.com
#开启pop3/smtp服务后的授权码 登录自己的qq邮箱点设置账户往下划就可以看见了
spring.mail.password=fdhgurtowakxjijds
spring.mail.default-encoding=UTF-8
#想要发送邮箱的一方
mail.fromMail.addr=12580007@qq.com

3.编写MailService 类

@Component
public class MailService {
	
	    private final Logger logger = LoggerFactory.getLogger(this.getClass());
	    @Autowired
	    private JavaMailSender mailSender;
	    @Value("${mail.fromMail.addr}")
	    private String from;
	    public void sendSimpleMail(String to, String subject, String content) {
	        SimpleMailMessage message = new SimpleMailMessage();
	        message.setFrom(from);
	        message.setTo(to);
	        message.setSubject(subject);
	        message.setText(content);
	        try {
	            mailSender.send(message);
	            logger.info("简单邮件已经发送。");
	        } catch (Exception e) {
	            logger.error("发送简单邮件时发生异常!", e);
	        }
	    }
	}

4.编写测试类在src/test/java目录下 使用测试要引入spring-boot-starter-test

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
	@Autowired
	private MailService mailService;
//	@Autowired
//	private TemplateEngine templateEngine;
	@Test
	public void testSimpleMail() throws Exception {
		mailService.sendSimpleMail("10068321@qq.com","邮件测试"," 愿你更好!!");
	}
}

到此就结束了
这个测试类你可以从页面获取 从controller获取数据在调用mailService.sendSimpleMail

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值