开发者

SpringBoot中邮件任务的使用

开发者 https://www.devze.com 2023-11-19 14:49 出处:网络 作者: yuhuofei2021
目录1. 引入依赖2. 更改配置3、编写测试类测试发送邮件1. 引入依赖 在项目的 pom.XML 文件中,引入下面的依赖
目录
  • 1. 引入依赖
  • 2. 更改配置
  • 3、编写测试类测试发送邮件

1. 引入依赖

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

<!--email依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependhttp://www.devze.comency>

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

SpringBoot中邮件任务的使用

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

SpringBoot中邮件任务的使用

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

测试类如下

package com.yuhuofei;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.bwww.devze.comoot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.Javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingExcepandroidtion;
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\\phpyuhuofei\\Desktop\\2.png"));
        //发送
        mailSender.send(message);
    }
}

测试结果

邮件能正常发送和接收

SpringBoot中邮件任务的使用

到此这篇关于SpringBoot中邮件任务的使用的文章就介绍到这了,更多相关SpringBoot邮件任务内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号