java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot邮件任务

SpringBoot中邮件任务的使用

作者:yuhuofei2021

这篇文章主要介绍了SpringBoot中邮件任务的使用,SpringBoot 邮件任务是指使用SpringBoot框架来实现邮件发送和接收的功能,通过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);
    }
}

测试结果

邮件能正常发送和接收

在这里插入图片描述

到此这篇关于SpringBoot中邮件任务的使用的文章就介绍到这了,更多相关SpringBoot邮件任务内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文