Java服务端开发3:SpringBoot发送邮件

前言:Spring提供了非常好用的JavaMailSender接口实现邮件发送。由于SpringBoot的Starter模块也为此提供了自动化配置,所以在引入了spring-boot-starter-mail依赖之后,会根据配置文件中的内容去创建JavaMailSender实例,因此我们可以直接在需要使用的地方直接@Autowired来引入邮件发送对象。

SpringBoot中发送邮件具体的使用步骤如下

1、添加Starter模块依赖

2、添加Spring Boot邮箱配置(QQ/网易163/Gmail)

3、调用JavaMailSender接口发送邮件

1、添加发送邮件需要的maven依赖

pom.xml 配置文件中加入 spring-boot-starter-mail 依赖。

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

2、添加邮箱配置参数

如其他自动化配置模块一样,在完成了依赖引入之后,只需要在application.properties中配置相应的属性内容。

下面我们以QQ邮箱为例,注意替换成自己的发件邮箱和授权码,关于如何获取授权码请点击这里:获取QQ邮箱授权码

#邮箱配置
#平台地址,这里用的是qq邮箱,使用其他邮箱请更换
spring.mail.host=smtp.qq.com
#发送邮件的邮箱地址:改成自己的邮箱
spring.mail.username=xxxxxxxxxxx
#发送短信后它给你的授权码 填写到这里
spring.mail.password=xxxxxxxxxxxx
#与发件邮箱一致
spring.mail.from=xxxxxxxxxxx

#下面不用改
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.default-encoding=UTF-8

3、调用JavaMailSender接口发送邮件

 由于Spring Boot的starter模块提供了自动化配置,所以在引入了spring-boot-starter-mail依赖之后,会根据配置文件中的内容去创建JavaMailSender实例,因此我们可以直接在需要使用的地方直接@Autowired来引入邮件发送对象。

直接上代码:

package com.hs.demo.mail;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * 发送邮件工具类 MailUtil
 *
 * @author heshi
 * @date 2021/3/22 16:52
 */

@Service
public class EmailUtil implements EmailService
{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //Spring Boot 提供了一个发送邮件的简单抽象,使用的是下面这个接口,这里直接注入即可使用
    @Autowired
    private JavaMailSender mailSender;

    // 配置文件中我的qq邮箱
    @Value("${spring.mail.from}")
    private String from;

    /**
     * 简单文本邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     */
    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        //创建SimpleMailMessage对象
        SimpleMailMessage message = new SimpleMailMessage();
        //邮件发送人
        message.setFrom(from);
        //邮件接收人
        message.setTo(to);
        //邮件主题
        message.setSubject(subject);
        //邮件内容
        message.setText(content);
        //发送邮件
        mailSender.send(message);
    }

    /**
     * html邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     */
    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        //获取MimeMessage对象
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper;
        try {
            messageHelper = new MimeMessageHelper(message, true);
            //邮件发送人
            messageHelper.setFrom(from);
            //邮件接收人
            messageHelper.setTo(to);
            //邮件主题
            message.setSubject(subject);
            //邮件内容,html格式
            messageHelper.setText(content, true);
            //发送
            mailSender.send(message);
            //日志信息
            logger.info("邮件已经发送。");
        } catch (MessagingException e) {
            logger.error("发送邮件时发生异常!", e);
        }
    }

    /**
     * 带附件的邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     * @param filePath 附件
     */
    @Override
    public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);
            mailSender.send(message);
            //日志信息
            logger.info("邮件已经发送。");
        } catch (MessagingException e) {
            logger.error("发送邮件时发生异常!", e);
        }


    }
}

单元测试:

package com.hs.demo;

import com.hs.demo.mail.EmailService;
import com.hs.demo.mail.EmailUtil;
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.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SendEmailApplicationTests {

    /**
     * 注入发送邮件的接口
     */
    @Autowired
    private EmailUtil mailService;

    /**
     * 测试发送文本邮件
     */
    @Test
    public void sendmail() {
        mailService.sendSimpleMail("[email protected]","主题:你好普通邮件","内容:第一封邮件");
    }

    @Test
    public void sendmailHtml(){
        mailService.sendHtmlMail("[email protected]","主题:你好html邮件","<h1>内容:第一封html邮件</h1>");
    }
}

效果图如下:


4、作用:常见的Web网站注册,邮箱点击链接验证激活如何实现?

Java实现用户注册邮箱激活验证

功能:通过邮箱注册账号,注册成功会向邮箱发送激活邮件。提示用户登录邮箱进行账户激活,方可使用账号。
流程:本质上就是向user表里新增一条数据,user表中应有一个code字段存放随机串。code在添加用户时随机生成(uuid),发送邮件时把code值带到邮件链接中用于查找唯一账户,然后判断用户状态,进行激活。

参考链接:

springboot发送邮件

java实现用户注册邮箱激活验证

猜你喜欢

转载自blog.csdn.net/CSDN2497242041/article/details/115113213