SpringBoot实现发送邮件功能

        平时注册或者登录一个网站时,可能收到过邮件用来发送验证码等,邮件在项目中经常会被用到,比如邮件发送通知,比如通过邮件注册,认证,找回密码,系统报警通知,报表信息等。

发送邮件用到了Spring Email的技术,我们这里使用的是SMTP。

1.邮箱打开SMTP服务

找一个邮箱用来给其他邮箱发送文件,要用SMTP服务发送邮件,所以邮箱要提前开启这个功能。

以163邮箱为例:(其他邮箱也是相同的操作)

开启SMTP服务后,会出现弹框,将授权密码记录下来,注意:只出现一次

SpringBoot实现发送邮件功能_第1张图片

还可以看到服务器地址 

SpringBoot实现发送邮件功能_第2张图片

2.SpringBoot集成Email

将下面的maven配置拷贝下来,集成到SpringBoot中。 



    org.springframework.boot
    spring-boot-starter-mail
    2.1.5.RELEASE

3.邮箱参数配置

首先进行配置文件,配置文件的目的是告诉Spring需要用哪个邮箱来发送邮件

写到SpringBoot的yaml配置文件里面

(登录授权密码不是你邮箱的密码,是你邮箱开启SMTP服务后显示的那个授权密码)

spring:
  mail:
    #邮箱域名、端口、邮箱账号、登录授权密码、启用smtps安全协议、采用ssl安全链接
    host: smtp.163.com
    port: 465
    username: ************@163.com
    password: ************
    protocol: smtps
    properties:
      mail.smtp.ssl.enable: true

4.发送邮件工具类

package com.kyw.util;
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.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;


@Component
public class MailClient {
    private static final Logger logger = LoggerFactory.getLogger(MailClient.class);

    @Autowired
    private JavaMailSender mailSender;

    //读取到配置类中的 “发送者”邮箱
    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送邮件
     * @param to        “接收者”邮箱
     * @param subject   邮件的主题
     * @param content   邮件的内容
     */
    public void sendMail(String to, String subject, String content) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setText(content,true);//表示可以发送HTML文件
            helper.setSubject(subject);
            mailSender.send(helper.getMimeMessage());
        } catch (MessagingException e) {
            logger.error("发送邮件失败:" + e.getMessage());
        }

    }
}

发送文本邮件测试

写一个测试类来测试,给我的qq邮箱发送一个邮件

package com.kyw;

import com.kyw.util.MailClient;
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.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes  = SpringBootDemoApplication.class)
public class MailTests {
    @Autowired
    private MailClient mailClient;

    @Test
    public void testTextMail() {
        mailClient.sendMail("[email protected]","TEST","测试,你好");
    }
}

收到啦

SpringBoot实现发送邮件功能_第3张图片

发送HTML邮件

也是用Thymeleaf实现的,没有配置Thymeleaf先去集成一下,搜索SpringBoot集成Thymeleaf即可。

先写一个邮件模板页面,里面的username是动态的值,等待后端调用的时候填充




  
  示例邮件


公司标志

欢迎来到我们的邮件示例

亲爱的收件人,

这是一个示例邮件的内容。您可以在这里添加任何您想要的信息。

感谢您的阅读。

祝您一切顺利!

访问我们的网站

后端测试类

package com.kyw;

import com.kyw.util.MailClient;
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.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes  = SpringBootDemoApplication.class)
public class MailTests {
    @Autowired
    private MailClient mailClient;

    /**
     *发送文本文件
     */
    @Test
    public void testTextMail() {
        mailClient.sendMail("[email protected]","TEST","测试,你好");
    }

    @Autowired
    private TemplateEngine templateEngine;

    /**
     *使用Thymeleaf 发送HTML邮件
     */
    @Test
    public void testHtmlMail() {
        Context context = new Context();
        context.setVariable("username","张三");

        String content =  templateEngine.process("/mail/maildemo",context);
        System.out.println(content);
        mailClient.sendMail("[email protected]","TEST",content);
    }
}

注意路径要按照Thymeleaf的规范来

SpringBoot实现发送邮件功能_第4张图片

SpringBoot实现发送邮件功能_第5张图片

你可能感兴趣的:(SpringBoot,spring,boot,java,后端)