【SpringBoot】9.SpringBoot中的邮件任务

1. 引入依赖

在项目的 pom.xml 文件中,引入下面的依赖

<!--email依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2. 更改配置

在 application.properties 配置文件中,配置好邮箱的信息,例如下面的

#邮箱配置
spring.mail.username=2162759651@qq.com
spring.mail.password=ejhvuqqibfrneafb
spring.mail.host=smtp.qq.com
spring.mail.properties.mail.smtp.ssl.enable=true

在这里插入图片描述
说明:这里用的是 qq 邮箱,需要开启 POP3/SMTP 服务,得到授权码,如果直接配置邮箱账号的明文密码登录,是无法登录的。

在这里插入图片描述

3、编写测试类测试发送邮件

测试类如下

package com.yuhuofei;

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 SpringbootSwaggerApplicationTests {

    @Autowired
    private JavaMailSenderImpl mailSender;

    //简单的邮件
    @Test
    void contextLoads() {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("邮件主题--测试");
        message.setText("这是邮件正文内容,测试SpringBoot的邮件任务!");
        message.setTo("2162759651@qq.com");
        message.setFrom("2162759651@qq.com");
        //发送
        mailSender.send(message);
    }

    //复杂的邮件
    @Test
    void contextLoadsMail() throws MessagingException {

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "utf-8");

        //标题及正文部分
        helper.setSubject("复杂邮件-测试");
        helper.setText("<p style='color:red'>这是邮件正文内容,测试SpringBoot的邮件任务!</p>", true);

        //附件
        helper.addAttachment("1.png", new File("C:\\Users\\yuhuofei\\Desktop\\1.png"));
        helper.addAttachment("2.png", new File("C:\\Users\\yuhuofei\\Desktop\\2.png"));
        //发送
        mailSender.send(message);
    }
}

测试结果

邮件能正常发送和接收

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值