java 实现发送邮件功能

今天分享一篇 java 发送 QQ 邮件的功能

环境:

jdk 1.8 + springboot 2.6.3 + maven 3.9.6

邮件功能依赖:

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

配置:

spring.mail.protocol=smtp
spring.mail.port=587
# qq邮箱
spring.mail.host=smtp.qq.com
# 发件人邮箱
spring.mail.username=xxx@qq.com
# 这里替换为自己的发件人邮箱的授权码
spring.mail.password=xxx
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

获取授权码:

登录 QQ 邮箱网页版 -> 设置 -> 账号

  

往下翻:找到下面这一块区域,如果没有开启服务的,直接开启服务即可 然后点击管理服务

 

 然后点击生成授权码

注意:生成后需要记住,授权码只展示这一次,如果忘了,可以生成多个

 

发送简单邮件

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.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Test1Controller {

    @Autowired
    private JavaMailSender mailSender;
    
    @Value("${from.email:xxx@qq.com}")
    private String fromEmail;
    
    @Value("${to.email:xxx@qq.com}")
    private String toEmail;

    @GetMapping("test")
    public void test() {
        sendSimpleMail();
    }

    public void sendSimpleMail() {

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(fromEmail); // 发件人邮箱
        message.setTo(toEmail);
        message.setSubject("主题:简单邮件");
        message.setText("内容:简单的邮件内容");

        mailSender.send(message);
    }
}

发送带附件的邮件

import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
public class Test1Controller {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${from.email:xxx@qq.com}")
    private String fromEmail;

    @Value("${to.email:xxx@qq.com}")
    private String toEmail;

    @GetMapping("test")
    public void test() {
        sendAttachmentsMail();
    }

    @SneakyThrows
    public void sendAttachmentsMail() {

        MimeMessage mimeMessage = mailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom(fromEmail);
        helper.setTo(toEmail);
        helper.setSubject("主题:有附件");
        helper.setText("内容:有附件的邮件");

        FileSystemResource file = new FileSystemResource(new File("C:\\Users\\11786\\Desktop\\blackground\\1.jpg"));
        // 这里可以上传多个文件,我这里就直接用一个文件了
        helper.addAttachment("file-1.jpg", file);
        helper.addAttachment("file-2.jpg", file);
        helper.addAttachment("file-2.jpg", file);
        mailSender.send(mimeMessage);
    }
}

使用 freemarker 发送模板邮件

在 resources -> templates -> email 目录下创建模板文件 template.ftl

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>邮件标题</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1 th:text="${username}">用户名</h1>
<p>这是一封模板邮件。</p>
</body>
</html>

发送邮件代码: 

import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.SneakyThrows;
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.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.internet.MimeMessage;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

@RestController
public class Test1Controller {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private Configuration freemarkerConfig;

    @Value("${from.email:xxx@qq.com}")
    private String fromEmail;

    @Value("${to.email:xxx@qq.com}")
    private String toEmail;

    @GetMapping("test")
    public void test() {
        sendTemplateMail();
    }

    @SneakyThrows
    public void sendTemplateMail() {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom(fromEmail);
        helper.setTo(toEmail);
        helper.setSubject("主题:模板邮件");

        // 创建数据模型
        Map<String, Object> model = new HashMap<>();
        model.put("username", "heyue");

        // 获取模板
        Template template = freemarkerConfig.getTemplate("email/template.ftl");

        // 渲染模板
        Writer out = new StringWriter();
        template.process(model, out);
        String htmlContent = out.toString();

        // 设置邮件内容
        helper.setText(htmlContent, true);

        // 发送邮件
        mailSender.send(mimeMessage);
    }
}

使用 thymeleaf 发送模板邮件

需要先引入依赖:

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

配置:

# 指定模板文件位置
spring.thymeleaf.prefix=classpath:/templates/email/
# 模板文件类型
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.template-resolver-order=1

在 resources -> templates -> email 目录下创建模板文件 template.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>邮件标题</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1 th:text="${username}">用户名</h1>
<p>这是一封模板邮件。</p>
</body>
</html>

发送邮件代码:

import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.internet.MimeMessage;
import java.io.StringWriter;

@RestController
public class Test1Controller {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private ApplicationContext applicationContext;

    @Value("${from.email:xxx@qq.com}")
    private String fromEmail;

    @Value("${to.email:xxx@qq.com}")
    private String toEmail;

    @GetMapping("test")
    public void test() {
        sendTemplateMail();
    }

    @SneakyThrows
    public void sendTemplateMail() {

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom(fromEmail);
        helper.setTo(toEmail);
        helper.setSubject("主题:模板邮件");

        // 获取 Thymeleaf 模板引擎
        TemplateEngine templateEngine = applicationContext.getBean(TemplateEngine.class);

        // 创建上下文并设置变量
        Context context = new Context();
        context.setVariable("username", "heyue");

        // 渲染模板
        StringWriter writer = new StringWriter();
        templateEngine.process("template", context, writer);
        String htmlContent = writer.toString();

        // 设置邮件内容
        helper.setText(htmlContent, true);

        // 发送邮件
        mailSender.send(mimeMessage);
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/484056.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

C语言分支和循环

目录 一.分支 一.if 二.if else 三.if else嵌套 四.else if 五.switch语句 二.循环 一.while (do while&#xff09;break : 二.for函数&#xff1a; 三.goto语句: 四.猜数字: 一.分支 一.if if要条件为真才执行为假不执行而且if只能执行后面第一条如果要执行多条就…

Windows下同时安装多个版本的JDK并配置环境变量

说明&#xff1a;这里安装的JDK版本为1.8和17 JDK下载 官方地址: https://www.oracle.com/java/ 我这里下载的是exe安装包 安装这里就不阐述了&#xff0c;安装方法都是一样的。 系统环境变量配置 1、首先新建JDK1.8和17的JAVA_HOME&#xff0c;他们的变量名区分开&#xff…

MySQL进阶——索引

索引 索引概述 索引结构 索引分类 索引语法 SQL性能分析 索引使用 索引设计原则 概述 介绍 索引&#xff08;Index&#xff09;是帮助MySQL高效获取数据的数据结构&#xff08;有序&#xff09;。 在数据之外&#xff0c;数据库系统还维护着满足特定查找算法的数据结…

Redis 教程系列之缓存雪崩,击穿,穿透(十四)

一,缓存雪崩 当大量缓存数据在同一时间过期(失效)或者 Redis 故障宕机时,如果此时有大量的用户请求,都无法在 Redis 中处理,于是全部请求都直接访问数据库,导致数据库的压力骤增,严重的会造成数据库宕机,从而形成一系列连锁反应,造成整个系统崩溃,这就是缓存雪崩的问…

AJAX介绍使用案例

文章目录 一、AJAX概念二、AJAX快速入门1、编写AjaxServlet&#xff0c;并使用response输出字符&#xff08;后台代码&#xff09;2、创建XMLHttpRequest对象&#xff1a;用于和服务器交换数据 & 3、向服务器发送请求 & 4、获取服务器响应数据 三、案例-验证用户是否存…

ubuntu上一款好用的串口工具screen

看名字&#xff0c;你猜他是什么&#xff1f; 安装 sudo apt install screen 然后将USB串口接到虚拟机&#xff0c;执行dmesg命令查看串口设备名&#xff1a; 测试&#xff1a; sudo screen /dev/ttyUSB0 115200确实很简单。

【C++】list类(使用方法和模拟实现)

一、标准库中的list类 1.1 list类介绍 1.2 list的常用接口 1.2.1 常用的构造函数 1.2.2 容量操作接口 &#xff08;1&#xff09;size &#xff08;2&#xff09;empty &#xff08;3&#xff09;resize 1.2.3 访问和遍历 &#xff08;1&#xff09;迭代器 &#xff…

DC-DC教程,真不错!

大家好&#xff0c;我是记得诚。 交流群读者分享了一个DC-DC的文档&#xff0c;内容还挺好&#xff0c;分享给大家。 文章原链接&#xff1a;DC-DC教程&#xff0c;真不错&#xff01;&#xff0c;可以获取完整的文档。 推荐阅读&#xff1a; 硬件工程师如何零基础入门&#…

数据结构:堆和二叉树遍历

堆的特征 1.堆是一个完全二叉树 2.堆分为大堆和小堆。大堆&#xff1a;左右节点都小于根节点 小堆&#xff1a;左右节点都大于根节点 堆的应用&#xff1a;堆排序&#xff0c;topk问题 堆排序 堆排序的思路&#xff1a; 1.升序排序&#xff0c;建小堆。堆顶就是这个堆最小…

【算法】五道大学生必备平价精致小众松弛感宝藏好题平替

【算法】五道大学生必备平价精致小众松弛感宝藏好题平替x ​ 刚学了Java就想用来写算法题的我&#xff1a; ​ 借着几道算法题&#xff0c;熟悉一下Java中Stack类&#xff0c;String类的用法。 925.长按键入 原题链接&#xff1a; 925. 长按键入 ​ 用来测试与练习String类自带…

php闭包应用

laravel 路由 bingTo 把路由URL映射到匿名回调函数上&#xff0c;框架会把匿名回调函数绑定到应用对象上&#xff0c;这样在匿名函数中就可以使用$this关键字引用重要的应用对象。Illuminate\Support\Traits\Macroable的__call方法。 自己写一个简单的demo: <?php <?…

遍历目录下的某个文件并删除

目录 需求 编写过程 演示 需求 大家在学习时可能会有一个自己的小目录&#xff0c;里面放着各种奇葩代码&#xff0c;有天突然发现&#xff0c;没有空间了&#xff0c;这时候发现遗留了很多的可执行文件&#xff0c;大大的浪费了我们的空间&#xff0c;但是由于层数深&#…

基于SSM的宠物领养平台的设计与实现

基于SSM的宠物领养平台的设计与实现 获取源码——》公主号&#xff1a;计算机专业毕设大全 获取源码——》公主号&#xff1a;计算机专业毕设大全

React腳手架已經創建好了,想使用Vite作為開發依賴

使用Vite作為開發依賴 安裝VITE配置VITE配置文件簡單的VITE配置項更改package.json中的scripts在根目錄中添加index.html現在可以瀏覽你的頁面了 安裝VITE 首先&#xff0c;在現有的React項目中安裝VITE npm install vite --save-dev || yarn add vite --dev配置VITE配置文件 …

JavaEE--小Demo--数据库建立

目录 实验准备 本次所要新建的文件 实验步骤 step1-demo.sql 1.在resources文件夹下新建demo.sql文件 2.打开此目录&#xff0c;并运行命令提示符 3.打开数据库mysql -uroot -p 4.创建数据库create database demo; 5.使用数据库use demo; 6.导入数据source demo.sql;…

Prometheus+Grafana 监控Tongweb7(by lqw)

文章目录 1.准备工作2.Tongweb7部署3.Prometheus部署4.上传jar包并配置Tongweb75.Prometheus配置6.安装和配置Grafana 1.准备工作 本次参考&#xff1a;Prometheus监控Tongweb容器 1.使用虚拟机ip&#xff1a;192.168.10.51&#xff08;tongweb&#xff09;&#xff0c;192.1…

算法系列--哈希表

&#x1f495;"白昼之光&#xff0c;岂知夜色之深。"&#x1f495; 作者&#xff1a;Mylvzi 文章主要内容&#xff1a;算法系列–哈希表 今天为大家带来的是算法系列--哈希表 1.两数之和 链接: https://leetcode.cn/problems/two-sum/submissions/515941642/ 分析…

《C++ Primer 第五版 中文版》第12章 动态内存【阅读笔记 + 个人思考】

《C Primer 第五版 中文版》第12章 动态内存【阅读笔记 个人思考】 12.1 动态内存与智能指针12.1.1 shared_ptr类 静态内存包括&#xff1a;初始化只读数据段&#xff0c;初始化读写数据段&#xff0c;未初始化数据和常量数据段。 详细在下面博客总结&#xff1a; Linux系统下…

吴恩达机器学习-可选实验室:Softmax函数

文章目录 CostTensorflow稀疏类别交叉熵或类别交叉熵祝贺 在这个实验室里&#xff0c;我们将探索softmax函数。当解决多类分类问题时&#xff0c;该函数用于Softmax回归和神经网络。 import numpy as np import matplotlib.pyplot as plt plt.style.use(./deeplearning.mplstyl…

【数据结构】顺序表和链表详解顺序表和链表的实现

主页&#xff1a;醋溜马桶圈-CSDN博客 专栏&#xff1a;数据结构_醋溜马桶圈的博客-CSDN博客 gitee&#xff1a;mnxcc (mnxcc) - Gitee.com 目录 1.线性表 1.1 顺序表 1.1.1 概念及结构 1.1.2 静态顺序表 1.1.3 动态顺序表 1.2 链表 1.2.1 链表的概念及结构 1.2.2 链表…
最新文章