java 实现发送邮件功能

news2024/9/28 21:23:35

今天分享一篇 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.coloradmin.cn/o/1541418.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

深度学习pytorch——多层感知机反向传播(持续更新)

在讲解多层感知机反向传播之前&#xff0c;先来回顾一下多输出感知机的问题&#xff0c;下图是一个多输出感知机模型&#xff1a; 课时44 反向传播算法-1_哔哩哔哩_bilibili 根据上一次的分析深度学习pytorch——感知机&#xff08;Perceptron&#xff09;&#xff08;持续更新…

pytorch 实现多层神经网络MLP(Pytorch 05)

一 多层感知机 最简单的深度网络称为多层感知机。多层感知机由 多层神经元 组成&#xff0c;每一层与它的上一层相连&#xff0c;从中接收输入&#xff1b;同时每一层也与它的下一层相连&#xff0c;影响当前层的神经元。 softmax 实现了 如何处理数据&#xff0c;如何将 输出…

【Godot4.2】基础知识 - Godot中的2D向量

概述 在Godot中&#xff0c;乃至一切游戏编程中&#xff0c;你应该都躲不开向量。这是每一个初学者都应该知道和掌握的内容&#xff0c;否则你将很难理解和实现某些其实原理非常简单的东西。 估计很多刚入坑Godot的小伙伴和我一样&#xff0c;不一定是计算机专业或编程相关专…

WSL使用

WSL使用 WSL安装和使用 Termianl和Ubuntu的安装 打开Hype-V虚拟化配置Microsoft Store中搜索Window Terminal并安装Microsoft Store中搜索Ubuntu, 选择安装Ubuntu 22.04.3 LTS版本打开Window Terminal选择Ubuntu标签栏, 进入命令行 中文输入法安装 查看是否安装了fcitx框架…

2023第13届上海生物发酵展8月7-9日举办

2024第13届国际生物发酵产品与技术装备展&#xff08;上海展&#xff09; 2024年8月7-9日|上海新国际博览中心 主办单位&#xff1a; 中国生物发酵产业协会 承办单位&#xff1a; 上海信世展览服务有限公司 院校支持&#xff1a; 北京工商大学 大连工业大学 华东理工大…

FakeLocation报虚拟位置服务连接失败,请重启设备再试

虚拟位置服务连接失败&#xff0c;请重启设备再试 最近遇到一个手机软件报的bug“虚拟位置服务连接失败&#xff0c;请重启设备再试” 因为我的实体“虚拟机”已经root&#xff0c;按道理是不可能报这个错的 折腾了2天&#xff0c;终于解决了 原来是这样&#xff0c;安装最新…

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配置文件 …

【MySQL】复合查询——基本单表查询、多表查询、自连接、子查询、使用from进行子查询、合并查询

文章目录 MySQL复合查询1. 基本单表查询2. 多表查询3. 自连接4. 子查询4.1 单行子查询4.2 多行子查询4.3 多列子查询4.4 使用from进行子查询 5. 合并查询5.1 union5.2 union all MySQL 复合查询 数据库的复合查询是指在一个查询中结合使用多个查询条件或查询子句&#xff0c;以…

常见技术难点及方案

1. 分布式锁 1.1 难点 1.1.1 锁延期 同一时间内不允许多个客户端同时获得锁&#xff1b; 1.1.2 防止死锁 需要确保在任何故障场景下&#xff0c;都不会出现死锁&#xff1b; 1.2.3 可重入 特殊的锁机制&#xff0c;它允许同一个线程多次获取同一个锁而不会被阻塞。 1.2…

五、分布式锁-redission

源码仓库地址&#xff1a;gitgitee.com:chuangchuang-liu/hm-dingping.git 1、redission介绍 目前基于redis的setnx特性实现的自定义分布式锁仍存在的问题&#xff1a; 问题描述重入问题同一个线程无法多次获取统一把锁。当方法A成功获取锁后&#xff0c;调用方法B&#xff0…

【C++】如何用一个哈希表同时封装出unordered_set与unordered_map

&#x1f440;樊梓慕&#xff1a;个人主页 &#x1f3a5;个人专栏&#xff1a;《C语言》《数据结构》《蓝桥杯试题》《LeetCode刷题笔记》《实训项目》《C》《Linux》《算法》 &#x1f31d;每一个不曾起舞的日子&#xff0c;都是对生命的辜负 目录 前言 1.哈希桶源码 2.哈希…

19.删除链表的倒数第N个结点 92.反转链表II

给你一个链表&#xff0c;删除链表的倒数第 n 个结点&#xff0c;并且返回链表的头结点。 示例 1&#xff1a; 输入&#xff1a;head [1,2,3,4,5], n 2 输出&#xff1a;[1,2,3,5]示例 2&#xff1a; 输入&#xff1a;head [1], n 1 输出&#xff1a;[]示例 3&#xff1a; …

模拟-算法

文章目录 替换所有的问号提莫攻击Z字形变换外观数列数青蛙 替换所有的问号 算法思路&#xff1a; 从前往后遍历整个字符串&#xff0c;找到问号之后&#xff0c;就遍历 a ~ z 去尝试替换即可。 class Solution {public String modifyString(String s) {char[] ss s.toCharA…

删除字符串--给你一个字符串S,要求你将字符串中出现的所有“gzu“子串删除,输出删除之后的S。

输入描述: 输入一行字符串S&#xff0c;长度不超过100。 输出描述: 输出进行删除操作之后的S。 #include <stdio.h> #include <stdlib.h> #include <string.h>//结合了串的模式匹配算法思路int main(){char s[100];char a[3]{g,z,u};gets(s);int nstrlen…

数据库语言一些基本操作

1&#xff0c;消除取值重复的行。 例如&#xff1a;查成绩不及格的学号&#xff1a;SELECT DISTINCT sno FROM SC WHERE grade<60. 这里使用DISTINCT表示取消取值重复的行。 2&#xff0c;比较。 例如&#xff1a;查计算机系全体学生的姓名&#xff1a;SELECT Sname FROM…

C++一维数组练习oj(3)

为什么C的一维数组练习要出要做那么多的题目&#xff1f;因为我们是竞赛学生&#xff01;想要将每个知识点灵活运用的话就必须刷大量的题目来锻炼思维。 我使用的是jsswoj.com这个刷题网站&#xff0c;当然要钱... C一维数组练习oj(2)-CSDN博客这是上一次的题目讲解 这道题有…

java每日一题——买啤酒(递归经典问题)

前言&#xff1a; 非常喜欢的一道题&#xff0c;经典中的经典。打好基础&#xff0c;daydayup!!!啤酒问题&#xff1a;一瓶啤酒2元&#xff0c;4个盖子可以换一瓶&#xff0c;2个空瓶可以换一瓶&#xff0c;请问10元可以喝几瓶 题目如下&#xff1a; 啤酒问题&#xff1a;一瓶…

[Halcon学习笔记]在Qt上实现Halcon窗口的字体设置颜色设置等功能

1、 Halcon字体大小设置在Qt上的实现 在之前介绍过Halcon窗口显示文字字体的尺寸和样式&#xff0c;具体详细介绍可回看 &#xff08;一&#xff09;Halcon窗口界面上显示文字的字体尺寸、样式修改 当时介绍的设定方法 //Win下QString Font_win "-Arial-10-*-1-*-*-1-&q…

传输层——UDP协议

端口号(Port) 端口号标识了一个主机上进行通信的不同的应用程序&#xff0c;准确来说&#xff0c;端口号标识了主机上唯一的一个进程。 在TCP/IP协议中, 用 "源IP", "源端口号", "目的IP", "目的端口号", "协议号" 这样一个…

罗德与施瓦茨联合广和通全面验证RedCap模组FG132系列先进性能

近日&#xff0c;罗德与施瓦茨联合广和通完成Redcap(Reduce Capability)功能和性能验证。本次测试使用R&SCMX500 OBT(One Box Tester)无线通信测试仪&#xff0c;主要验证广和通RedCap模组FG132系列射频性能以及IP层吞吐量&#xff0c;包括RedCap上下行吞吐量和射频指标如矢…