Java笔记:SpringBoot发送邮件(1)

简介: Java笔记:SpringBoot发送邮件

SpringBoot发送邮件

课程目录

1、第一部分 背景

  • 使用场景
  • 发送原理
  • 发送历史
  • SpringBoot介绍
  • 前置知识

2、第二部分 实践

  • 文本邮件
  • HTML邮件
  • 附件邮件
  • 图片邮件
  • 邮件模板
  • 邮件系统

第一部分 背景

1、邮件使用场景

  • 注册验证
  • 网站营销
  • 安全防线
  • 提醒监控
  • 触发机制

2、邮件发送原理

  • SMPTP协议 发送协议
  • POP3协议 接收协议
  • IMAP协议 对POP3补充
  • Mime协议

3、邮件发送历史

  • 1969年10月世界第一封
  • 1987年9月14日中国第一封

4、SpringBoot介绍

  • 约定大于配置
  • 简单快速开发
  • 强大生态链

5、前置知识

  • Spring
  • Maven
  • HTML
  • Thymeleaf

第二部分 实践

1、学习路径

  • 基础配置
  • 文本邮件
  • HTML邮件
  • 附件邮件
  • 图片邮件
  • 邮件模板
  • 异常处理
  • 邮件系统

2、环境配置

初始化SpringBoot项目

https://start.spring.io/

版本:2.3.5.RELEASE

Service示例

package com.example.demo.service;
import org.springframework.stereotype.Service;
@Service
public class HelloService {
    public void sayHello(){
        System.out.println("Hello");
    }
}

测试类

package com.example.demo;
import com.example.demo.service.HelloService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DemoApplicationTests {
    @Autowired
    HelloService helloService;
    @Test
    void sayHelloTest() {
        helloService.sayHello();
    }
}

3、项目配置

  • 引入jar包
<!-- 邮件 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- 模板引擎 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  • 配置邮箱参数
spring.mail.host=smtp.163.com
spring.mail.username=username@163.com
# 户端授权码
spring.mail.password=password
spring.mail.default-encoding=UTF-8

4、发送邮件

  • 封装SimpleMailMessage
  • JavaMailSender进行发送
package com.example.demo.service;
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;
@Service
public class MailService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Value("${spring.mail.username}")
    private String fromUser;
    @Autowired
    private JavaMailSender mailSender;
    /**
     * 文本邮件
     *
     * @param toUser
     * @param subject
     * @param content
     */
    public void sendSimpleMail(
            String toUser, String subject,
            String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(fromUser);
        message.setTo(toUser);
        message.setSubject(subject);
        message.setText(content);
        mailSender.send(message);
    }
    /**
     * html邮件
     *
     * @param toUser
     * @param subject
     * @param content
     */
    public void sendHtmlMail(
            String toUser, String subject,
            String content) {
        logger.info("html邮件开始:{} {} {}", toUser, subject, content);
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(fromUser);
            helper.setTo(toUser);
            helper.setSubject(subject);
            helper.setText(content, true);
            mailSender.send(message);
            logger.info("html邮件成功");
        } catch (MessagingException e) {
            e.printStackTrace();
            logger.error("html邮件失败:", e);
        }
    }
    /**
     * 附件邮件
     *
     * @param toUser
     * @param subject
     * @param content
     * @param filePath 绝对路径
     * @throws MessagingException
     */
    public void sendAttachmentsMail(
            String toUser, String subject,
            String content, String filePath)
            throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(fromUser);
        helper.setTo(toUser);
        helper.setSubject(subject);
        helper.setText(content, true);
        FileSystemResource file = new FileSystemResource(new File(filePath));
        // 可以多次添加附件
        helper.addAttachment(file.getFilename(), file);
        mailSender.send(message);
    }
    /**
     * 图片邮件
     *
     * @param toUser
     * @param subject
     * @param content
     * @param resourcePath
     * @param resourceId
     * @throws MessagingException
     */
    public void sendInlineResourceMail(
            String toUser, String subject,
            String content, String resourcePath, String resourceId)
            throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(fromUser);
        helper.setTo(toUser);
        helper.setSubject(subject);
        helper.setText(content, true);
        FileSystemResource resource = new FileSystemResource(new File(resourcePath));
        // 可以多次添加图片
        helper.addInline(resourceId, resource);
        mailSender.send(message);
    }
}
  • 发送测试
package com.example.demo;
import com.example.demo.service.MailService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.ClassPathResource;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.MessagingException;
import java.io.IOException;
@SpringBootTest
class DemoApplicationTests {
    @Autowired
    MailService mailService;
    @Autowired
    TemplateEngine templateEngine;
    @Test
    void sendSimpleMailTest() {
        mailService.sendSimpleMail(
                "pengshiyuyx@163.com",
                "文本邮件标题",
                "邮件内容"
        );
    }
    @Test
    void sendHtmlMailTest() {
        String content = "<html>" +
                "<body>" +
                "<h3>这是邮件内容</h3>" +
                "</body>" +
                "</html>";
        mailService.sendHtmlMail(
                "pengshiyuyx@163.com",
                "HTML邮件标题",
                content
        );
    }
    @Test
    void sendAttachmentsMailTest() throws MessagingException, IOException {
        String filePath = "name.txt";
        ClassPathResource resource = new ClassPathResource(filePath);
        mailService.sendAttachmentsMail(
                "pengshiyuyx@163.com",
                "附件邮件标题",
                "邮件内容",
                resource.getFile().getAbsolutePath()
        );
    }
    @Test
    void sendInlineResourceMailTest() throws IOException, MessagingException {
        String imagePath = "demo.jpg";
        String resourceId = "image001";
        String content = "<html>" +
                "<body>" +
                "<h3>这是邮件内容</h3>" +
                "<img src='cid:" + resourceId + "'>" +
                "</body>" +
                "</html>";
        ClassPathResource resource = new ClassPathResource(imagePath);
        mailService.sendInlineResourceMail(
                "pengshiyuyx@163.com",
                "图片邮件标题",
                content,
                resource.getFile().getAbsolutePath(),
                resourceId
        );
    }
    @Test
    void sendTemplateMailTest() {
        Context content = new Context();
        content.setVariable("id", "007");
        String mailContent = templateEngine.process("mail", content);
        mailService.sendHtmlMail(
                "pengshiyuyx@163.com",
                "模板邮件标题",
                mailContent
        );
    }
}

模板

<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org/">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>
    <p>感谢注册</p>
    <p><a href="" th:href="@{https://www.baidu.com/{id}(id=${id})}">点击激活</a></p>
</body>
</html>

常见错误


421 HL:ICC 该IP同事并发连接数过大

451 Requested mail action not taken: too much fail

登录失败次数过多,被临时禁止登录

553 authentication is required 认证失败

更多错误

http://help.163.com/09/1224/17/5RAJ4LMH00753VB8.html

邮件系统

  • 独立微服务MQ
  • 异常处理
  • 定时重试邮件
  • 异步发送

总结

  • 邮件发送历史和原理
  • SpringBoot 和邮件系统
  • 各种类型邮件的发送
  • 邮件系统
相关文章
|
2月前
|
Java 数据库连接 API
Java 8 + 特性及 Spring Boot 与 Hibernate 等最新技术的实操内容详解
本内容涵盖Java 8+核心语法、Spring Boot与Hibernate实操,按考试考点分类整理,含技术详解与代码示例,助力掌握最新Java技术与应用。
90 2
|
3月前
|
Java 数据库连接 API
Java 对象模型现代化实践 基于 Spring Boot 与 MyBatis Plus 的实现方案深度解析
本文介绍了基于Spring Boot与MyBatis-Plus的Java对象模型现代化实践方案。采用Spring Boot 3.1.2作为基础框架,结合MyBatis-Plus 3.5.3.1进行数据访问层实现,使用Lombok简化PO对象,MapStruct处理对象转换。文章详细讲解了数据库设计、PO对象实现、DAO层构建、业务逻辑封装以及DTO/VO转换等核心环节,提供了一个完整的现代化Java对象模型实现案例。通过分层设计和对象转换,实现了业务逻辑与数据访问的解耦,提高了代码的可维护性和扩展性。
143 1
|
3月前
|
Java 调度 流计算
基于Java 17 + Spring Boot 3.2 + Flink 1.18的智慧实验室管理系统核心代码
这是一套基于Java 17、Spring Boot 3.2和Flink 1.18开发的智慧实验室管理系统核心代码。系统涵盖多协议设备接入(支持OPC UA、MQTT等12种工业协议)、实时异常检测(Flink流处理引擎实现设备状态监控)、强化学习调度(Q-Learning算法优化资源分配)、三维可视化(JavaFX与WebGL渲染实验室空间)、微服务架构(Spring Cloud构建分布式体系)及数据湖建设(Spark构建实验室数据仓库)。实际应用中,该系统显著提升了设备调度效率(响应时间从46分钟降至9秒)、设备利用率(从41%提升至89%),并大幅减少实验准备时间和维护成本。
234 0
|
3月前
|
Java API 微服务
Java 21 与 Spring Boot 3.2 微服务开发从入门到精通实操指南
《Java 21与Spring Boot 3.2微服务开发实践》摘要: 本文基于Java 21和Spring Boot 3.2最新特性,通过完整代码示例展示了微服务开发全流程。主要内容包括:1) 使用Spring Initializr初始化项目,集成Web、JPA、H2等组件;2) 配置虚拟线程支持高并发;3) 采用记录类优化DTO设计;4) 实现JPA Repository与Stream API数据访问;5) 服务层整合虚拟线程异步处理和结构化并发;6) 构建RESTful API并使用Springdoc生成文档。文中特别演示了虚拟线程配置(@Async)和StructuredTaskSco
353 0
|
3月前
|
监控 安全 Java
Java 开发中基于 Spring Boot 3.2 框架集成 MQTT 5.0 协议实现消息推送与订阅功能的技术方案解析
本文介绍基于Spring Boot 3.2集成MQTT 5.0的消息推送与订阅技术方案,涵盖核心技术栈选型(Spring Boot、Eclipse Paho、HiveMQ)、项目搭建与配置、消息发布与订阅服务实现,以及在智能家居控制系统中的应用实例。同时,详细探讨了安全增强(TLS/SSL)、性能优化(异步处理与背压控制)、测试监控及生产环境部署方案,为构建高可用、高性能的消息通信系统提供全面指导。附资源下载链接:[https://pan.quark.cn/s/14fcf913bae6](https://pan.quark.cn/s/14fcf913bae6)。
487 0
|
Java 测试技术 数据安全/隐私保护
Springboot 系列(十三)使用邮件服务
Springboot 系列(十三)使用邮件服务
343 0
Springboot 系列(十三)使用邮件服务
|
Java Spring 数据安全/隐私保护
springboot--邮件服务
发送邮件应该是网站的必备功能之一,什么注册验证,忘记密码或者是给用户发送营销信息。最早期的时候我们会使用JavaMail相关api来写发送邮件的相关代码,后来spring退出了JavaMailSender更加简化了邮件发送的过程,在之后springboot对此进行了封装就有了现在的spring-boot-starter-mail,本章文章的介绍主要来自于此包。
1970 0
|
Java Spring 开发工具
spring boot和邮件服务
1.运行环境 开发工具:intellij idea JDK版本:1.8 项目管理工具:Maven 4.0.0 2.GITHUB地址 .pro_name a { color: #4183c4 } .osc_git_title { background-color: #fff } .
951 0