当前位置:   article > 正文

springboot整合邮件服务

springboot整合邮件服务

申请密匙

在这里插入图片描述
发送短信,会生成一行字符。

导进邮件服务的依赖

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
  • 1
  • 2
  • 3
  • 4

application.properties

#邮箱类型
spring.mail.host=smtp.qq.com
#邮箱名字
spring.mail.username=codel115@qq.com
#邮箱的密匙  【需要去相关的邮箱里面申请】
spring.mail.password=申请是密匙

spring.mail.default-encoding=UTF-8

#自定义的数据  【邮件发送人】
mail.from=codel11158@qq.com
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

创建service和相对应的impl测试类

service接口

public interface MailService {
    void sendSimpleMail(String mail);
}

  • 1
  • 2
  • 3
  • 4

impl实现类

package com.codel.mail.sersvice.impl;

import com.codel.mail.sersvice.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

/**
 * 邮件服务impl
 * 需要先构建 SimpleMailMessage或 MimeMessage邮件信息类来填写邮件标题、邮件内容等信息,
 * 最后提交给JavaMailSenderImpl发送邮件,
 *
 * @author codel
 * @date 2021/09/23
 */
@Service
@Slf4j
public class MailServiceImpl implements MailService {
//    JavaMailSender 实现  MailSender 拥有发送文件的功能
    @Autowired
    private JavaMailSender mailSender;
    @Value("${mail.from}")
    private String mailFrom;

    /**
     * 发送简单的邮件
     * mailFrom 是发件人,
     * mailTo 是收件人。
     * message.setSubject()设置邮件主题。
     * message.setText()设置邮件内容。
     * mailSender.send(message)是发送短信。
     * @param mailTo 邮件
     */
    @Override
    public void sendSimpleMail(String mailTo) {
        //创建邮件  SimpleMailMessage是创建文件 包括内容,邮件消息,发件人,收件人……
        SimpleMailMessage message = new SimpleMailMessage();

        message.setFrom(mailFrom);
        message.setTo(mailTo);
        message.setSubject("simple mail");
        message.setText("hello world");

        //发送邮件
        mailSender.send(message);
        log.info("邮件已经发送");
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52

Spring 自带了一个 MailSender 的实现 JavaMailSenderImpl,它会使用 JavaMail API 来发送 Email。Spring 或 SpringBoot 应用在发送 Email 之前,我们必须要JavaMailSenderImpl 装配为 Spring应用上下文的一个 bean。

controller类


package com.codel.mail.controller;

import com.codel.mail.sersvice.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 邮件控制器
 *
 * @author codel
 * @date 2021/09/23
 */
@RestController
@RequestMapping("/mail")
public class MailController {

    @Autowired
    private MailService mailService;

    /**
     * 发送邮件
     *
     * @param userName 用户名
     *  把接收人的信息传递进去
     * @return {@link String}
     */
    @GetMapping("/send")
    public String sendMail(@RequestParam(value = "userName") String userName) {
        mailService.sendSimpleMail(userName);
        return "success";
    }
}



  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

理解:就是导进依赖,就拥有了mail的功能了,也就是拥有了邮件服务的包了,然后邮件包括编写有邮件,发送邮件,检查文件,保存文件的功能,这个包里面就会拥有这些功能,然后配置相关的属性就会激活功能。

上面是邮件的文字发送,

创建多一个接口,实现附件的发送。


public interface MailService {
    void sendSimpleMail(String mail);
    void sendMail(String mail);
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

service类

 /**
     * 发送附件邮件
     * MimeMessage 比 SimpleMailMessage 功能更强大,可以发送附件,也可以将内容转成html 格式发送。
     * 所以一般实际使用的时候都使用MimeMessage。
     * 另外发送附件,还需要借助MimeMessageHelper 。
     * MimeMessageHelper是辅助MimeMessage的。
     *
     * @param mail 邮件
     */
    @Override
    public void sendMail(String mail) {
//
        MimeMessage message=mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(mailFrom);
            helper.setTo(mail);
            helper.setSubject("simple mail");
            helper.setText("hello world", true);
            FileSystemResource file = new FileSystemResource(new File("D:\\大四\\1.png"));
            String fileName = file.getFilename();
            //判断是否为空
            assert fileName != null;
           // helper.addAttachment()是添加附件的。
            helper.addAttachment(fileName, file);
            mailSender.send(message);
            log.info("附件邮件已经发送");
        } catch ( MessagingException e) {
            log.error("{}",e);
        }
    }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

controller类

 /**
     * 发送附件电子邮件
     *
     * @param username 用户名
     * @return {@link String}
     */
    @GetMapping("/sendEmail/{username}")
    public String sendEmail(@PathVariable("username") String username){
        mailService.sendMail(username);
        return "附件文件发送成功";
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

运行结果:
在这里插入图片描述


简单的文字邮件和附件邮件完成。

模板邮件推送

导入模板引擎依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
  • 1
  • 2
  • 3
  • 4

配置模板页面

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户验证码</title>
</head>
<body>
<div><span th:text="${username}">XXX</span>&nbsp;先生/女士,您好: </div>
<p style="text-indent: 2em">您的用户验证码为<span th:text="${code}" style="color: cornflowerblue">123456</span>,请妥善保管。></p>
</body>
</html>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

username和code两个动态变量都是和controller后台绑定的。

定制邮件发送服务

    /**
     * 发送电子邮件模板
     *
     * @param to      收件人
     * @param subject 主题
     * @param content 内容
     */
    @Override
    public void sendTemplateEmail(String to, String subject, String content) {

        MimeMessage message = mailSender.createMimeMessage();
        try {
            //使用MimeMessageHelper帮助类并设置multpart多部件使用为true
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(mailFrom);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            //发送邮件
            mailSender.send(message);
            System.out.println("模板邮件发送成功!");
        } catch (MessagingException e) {
            System.out.println("模板邮件发送失败");
            e.printStackTrace();
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

这里的收件人可以使用一个数组来接收,就是说可以多人接收同一个邮件。

模拟测试传递信息

 /**
     * 测试发送模板邮件
     */
    @Autowired
    private MailServiceImpl mailService;
    @Autowired
    private TemplateEngine templateEngine;

    @Test
    public void sendTemplateEmail() {
        String to = "codel1115@qq.com";
        String subject = "【模板邮件】标题";

        //使用模板定制邮件正文内容
        Context context = new Context();
        context.setVariable("username", "codeL");
        context.setVariable("code", "489");

        //使用TemplateEngline设置要处理的模板 页面
        String emailTemplate = templateEngine.process("test", context);

        //发送模板邮件
        mailService.sendTemplateEmail(to, subject, emailTemplate);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

测试结果:
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/95359
推荐阅读
相关标签
  

闽ICP备14008679号