Hutool Hutool
首页
指南
  • 核心(Hutool-core)
  • 配置文件(Hutool-setting)
  • 日志(Hutool-log)
  • 缓存(Hutool-cache)
  • JSON(Hutool-json)
  • 加密解密(Hutool-crypto)
  • DFA查找(Hutool-dfa)
  • 数据库(Hutool-db)
  • HTTP客户端(Hutool-http)
  • 定时任务(Hutool-cron)
  • 扩展(Hutool-extra)
  • 布隆过滤(Hutool-bloomFilter)
  • 切面(Hutool-aop)
  • 脚本(Hutool-script)
  • Office文档操作(Hutool-poi)
  • 系统调用(Hutool-system)
  • 图形验证码(Hutool-captcha)
  • 网络Socket(Hutool-socket)
  • JWT(Hutool-jwt)
支持
更新记录 (opens new window)
GitHub (opens new window)
首页
指南
  • 核心(Hutool-core)
  • 配置文件(Hutool-setting)
  • 日志(Hutool-log)
  • 缓存(Hutool-cache)
  • JSON(Hutool-json)
  • 加密解密(Hutool-crypto)
  • DFA查找(Hutool-dfa)
  • 数据库(Hutool-db)
  • HTTP客户端(Hutool-http)
  • 定时任务(Hutool-cron)
  • 扩展(Hutool-extra)
  • 布隆过滤(Hutool-bloomFilter)
  • 切面(Hutool-aop)
  • 脚本(Hutool-script)
  • Office文档操作(Hutool-poi)
  • 系统调用(Hutool-system)
  • 图形验证码(Hutool-captcha)
  • 网络Socket(Hutool-socket)
  • JWT(Hutool-jwt)
支持
更新记录 (opens new window)
GitHub (opens new window)
  • 快速入门

    • 简介
  • 核心(Hutool-core)

    • 克隆

      • 支持泛型的克隆接口和克隆类
    • 类型转换

      • 类型转换工具类-Convert
      • 自定义类型转换-ConverterRegistry
    • 日期时间

      • 概述
      • 日期时间工具-DateUtil
      • 日期时间对象-DateTime
      • 农历日期-ChineseDate
      • LocalDateTime工具-LocalDateTimeUtil
      • 计时器工具-TimeInterval
    • IO流相关

      • 概述
      • IO工具类-IoUtil
      • 文件工具类-FileUtil
      • 文件监听-WatchMonitor
      • 文件类型判断-FileTypeUtil
      • 文件

        • 文件读取-FileReader
        • 文件写入-FileWriter
        • 文件追加-FileAppender
        • 文件跟随-Tailer
        • 文件名工具-FileNameUtil
      • 资源

        • 概述
        • 资源工具-ResourceUtil
        • ClassPath资源访问-ClassPathResource
    • 工具类

      • 概述
      • 字符串工具-StrUtil
      • 16进制工具-HexUtil
      • Escape工具-EscapeUtil
      • Hash算法-HashUtil
      • URL工具-URLUtil
      • XML工具-XmlUtil
      • 对象工具-ObjectUtil
      • 反射工具-ReflectUtil
      • 泛型类型工具-TypeUtil
      • 分页工具-PageUtil
      • 剪贴板工具-ClipboardUtil
      • 类工具-ClassUtil
      • 枚举工具-EnumUtil
      • 命令行工具-RuntimeUtil
      • 数字工具-NumberUtil
      • 数组工具-ArrayUtil
      • 随机工具-RandomUtil
      • 唯一ID工具-IdUtil
      • 压缩工具-ZipUtil
      • 引用工具-ReferenceUtil
      • 正则工具-ReUtil
      • 身份证工具-IdcardUtil
      • 信息脱敏工具-DesensitizedUtil
      • 社会信用代码工具-CreditCodeUtil
      • SPI加载工具-ServiceLoaderUtil
      • 字符编码工具-CharsetUtil
      • 类加载工具-ClassLoaderUtil
    • 语言特性

      • 概述
      • HashMap扩展-Dict
      • 单例工具-Singleton
      • 断言-Assert
      • 二进码十进数-BCD
      • 控制台打印封装-Console
      • 字段验证器-Validator
      • 字符串格式化-StrFormatter
      • 树结构

        • 树结构工具-TreeUtil
    • JavaBean

      • 概述
      • Bean工具-BeanUtil
      • DynaBean
      • 表达式解析-BeanPath
      • Bean描述-BeanDesc
      • 空检查属性获取-Opt
    • 集合类

      • 概述
      • 集合工具-CollUtil
      • 列表工具-ListUtil
      • Iterator工具-IterUtil
      • 有界优先队列-BoundedPriorityQueue
      • 线程安全的HashSet-ConcurrentHashSet
      • 集合串行流工具-CollStreamUtil
      • 行遍历器-LineIter
    • Map

      • 概述
      • Map工具-MapUtil
      • 双向查找Map-BiMap
      • 可重复键值Map-TableMap
      • Map流式构建器-MapBuilder copy
    • Codec编码

      • Base62编码解码-Base62
      • Base64编码解码-Base64
      • Base32编码解码-Base32
      • 莫尔斯电码-Morse
      • BCD码-BCD
      • 回转N位密码-Rot
      • Punycode实现-PunyCode
    • 文本操作

      • CSV文件处理工具-CsvUtil
      • Unicode编码转换工具-UnicodeUtil
      • 可复用字符串生成器-StrBuilder
      • 字符串切割-StrSplitter
    • 注解

      • 注解工具-AnnotationUtil
    • 比较器

      • 概述
      • 比较工具-CompareUtil
      • 版本比较器-VersionComparator
    • 异常

      • 异常工具-ExceptionUtil
      • 其它异常封装
    • 数学

      • 数学相关-MathUtil
    • 线程和并发

      • 线程工具-ThreadUtil
      • 异步工具类-AsyncUtil
      • 自定义线程池-ExecutorBuilder
      • 高并发测试-ConcurrencyTester
    • 图片

      • 图片工具-ImgUtil
      • 图片编辑器-Img
    • 网络

      • 网络工具-NetUtil
      • URL生成器-UrlBuilder
    • 源码编译

      • 源码编译工具-CompilerUtil
  • 配置文件(Hutool-setting)

    • 概述
    • Properties扩展-Props
    • 设置文件-Setting
  • 日志(Hutool-log)

    • 概述
    • 日志工厂-LogFactory
    • 疑惑解答
    • 静态调用日志-StaticLog
  • 缓存(Hutool-cache)

    • 概述
    • 缓存工具-CacheUtil
    • 先入先出-FIFOCache
    • 文件缓存-FileCache
    • 最少使用-LFUCache
    • 最近最久未使用-LRUCache
    • 超时-TimedCache
    • 弱引用-WeakCache
  • JSON(Hutool-json)

    • 概述
    • JSON工具-JSONUtil
    • JSON对象-JSONObject
    • JSON数组-JSONArray
  • 加密解密(Hutool-crypto)

    • 概述
    • 加密解密工具-SecureUtil
    • 国密算法工具-SmUtil
    • 对称加密-SymmetricCrypto
    • 摘要加密-Digester
    • 消息认证码算法-HMac
    • 签名和验证-Sign
    • 非对称加密-AsymmetricCrypto
  • DFA查找(Hutool-dfa)

    • 概述
    • DFA查找
  • 数据库(Hutool-db)

    • 概述
    • SQL执行器-SqlExecutor
    • 支持事务的CRUD-Session
    • 数据库简单操作-Db
    • 数据源工厂-DsFactory
    • 数据源配置db.setting样例
    • 案例1-导出Blob字段图像
    • 常见问题
    • NoSQL

      • Redis客户端封装-RedisDS
      • MongoDB客户端封装-MongoDS
  • HTTP客户端(Hutool-http)

    • 概述
    • Http客户端工具类-HttpUtil
    • HTML工具类-HtmlUtil
    • Http响应-HttpResponse
    • Http请求-HttpRequest
    • UA工具类-UserAgentUtil
    • 常用Http状态码-HttpStatus
    • 案例1-爬取开源中国的开源资讯
    • 常见问题
    • Server

      • 简易Http服务器-SimpleServer
    • WebService

      • Soap客户端-SoapClient
  • 定时任务(Hutool-cron)

    • 概述
    • 全局定时任务-CronUtil
  • 扩展(Hutool-extra)

    • 概述
    • Servlet工具-ServletUtil
    • 二维码工具-QrCodeUtil
    • 邮件工具-MailUtil
      • 概述
      • 使用
        • 引入依赖
        • 邮件服务器配置
      • 发送邮件
        • 其它
    • cglib

      • Cglib工具-CglibUtil
    • emoji

      • Emoji工具-EmojiUtil
    • FTP

      • FTP客户端封装-Ftp
      • 简易FTP服务器-SimpleFtpServer
    • Jsch封装

      • SFTP封装-Sftp
      • Jsch工具-JschUtil
    • Spring

      • Spring工具-SpringUtil
    • 中文分词

      • 中文分词封装-TokenizerUtil
    • 压缩

      • 压缩封装-CompressUtil
    • 拼音

      • 拼音工具-PinyinUtil
    • 表达式引擎

      • 表达式引擎封装-ExpressionUtil
    • 模板引擎

      • 模板引擎封装-TemplateUtil
  • 布隆过滤(Hutool-bloomFilter)

    • 概述
  • 切面(Hutool-aop)

    • 概述
    • 切面代理工具-ProxyUtil
  • 脚本(Hutool-script)

    • 概述
    • Script工具-ScriptUtil
  • Office文档操作(Hutool-poi)

    • 概述
    • Excel工具-ExcelUtil
    • Excel生成-ExcelWriter
    • Excel大数据生成-BigExcelWriter
    • Excel读取-ExcelReader
    • Word生成-Word07Writer
    • 流方式读取Excel2003-Excel03SaxReader
    • 流方式读取Excel2007-Excel07SaxReader
  • 系统调用(Hutool-system)

    • 系统属性调用-SystemUtil
    • Oshi封装-OshiUtil
  • 图形验证码(Hutool-captcha)

    • 概述
  • 网络Socket(Hutool-socket)

    • 概述
    • AIO封装-AioServer和AioClient
    • NIO封装-NioServer和NioClient
  • JWT(Hutool-jwt)

    • 概述
    • JWT工具-JWTUtil
    • JWT签名工具-JWTSignerUtil
    • JWT验证-JWTValidator
  • 指南
  • 扩展(Hutool-extra)
Hutool
2023-03-28
目录

邮件工具-MailUtil

特别赞助 by:

# 概述

在Java中发送邮件主要品依靠javax.mail包,但是由于使用比较繁琐,因此Hutool针对其做了封装。由于依赖第三方包,因此将此工具类归类到extra模块中。

# 使用

# 引入依赖

Hutool对所有第三方都是可选依赖,因此在使用MailUtil时需要自行引入第三方依赖。

<dependency>
	<groupId>com.sun.mail</groupId>
	<artifactId>javax.mail</artifactId>
	<version>1.6.2</version>
</dependency>

说明 com.sun.mail是javax.mail升级后的版本,新版本包名做了变更。

# 邮件服务器配置

在classpath(在标准Maven项目中为src/main/resources)的config目录下新建mail.setting文件,最小配置内容如下,在此配置下,smtp服务器和用户名都将通过from参数识别:

# 发件人(必须正确,否则发送失败)
from = hutool@yeah.net
# 密码(注意,某些邮箱需要为SMTP服务单独设置密码,详情查看相关帮助)
pass = q1w2e3

有时候一些非标准邮箱服务器(例如企业邮箱服务器)的smtp地址等信息并不与发件人后缀一致,端口也可能不同,此时Hutool可以提供完整的配置文件:

完整配置

# 邮件服务器的SMTP地址,可选,默认为smtp.<发件人邮箱后缀>
host = smtp.yeah.net
# 邮件服务器的SMTP端口,可选,默认25
port = 25
# 发件人(必须正确,否则发送失败)
from = hutool@yeah.net
# 用户名,默认为发件人邮箱前缀
user = hutool
# 密码(注意,某些邮箱需要为SMTP服务单独设置授权码,详情查看相关帮助)
pass = q1w2e3

注意 邮件服务器必须支持并打开SMTP协议,详细请查看相关帮助说明 配置文件的样例中提供的是我专门为测试邮件功能注册的yeah.net邮箱,帐号密码公开,供Hutool用户测试使用。

# 发送邮件

  1. 发送普通文本邮件,最后一个参数可选是否添加多个附件:
MailUtil.send("hutool@foxmail.com", "测试", "邮件来自Hutool测试", false);
  1. 发送HTML格式的邮件并附带附件,最后一个参数可选是否添加多个附件:
MailUtil.send("hutool@foxmail.com", "测试", "<h1>邮件来自Hutool测试</h1>", true, FileUtil.file("d:/aaa.xml"));
  1. 群发邮件,可选HTML或普通文本,可选多个附件:
ArrayList<String> tos = CollUtil.newArrayList(
	"person1@bbb.com", 
	"person2@bbb.com", 
	"person3@bbb.com", 
	"person4@bbb.com");

MailUtil.send(tos, "测试", "邮件来自Hutool群发测试", false);

发送邮件非常简单,只需一个方法即可搞定其中按照参数顺序说明如下:

  1. tos: 对方的邮箱地址,可以是单个,也可以是多个(Collection表示)
  2. subject:标题
  3. content:邮件正文,可以是文本,也可以是HTML内容
  4. isHtml: 是否为HTML,如果是,那参数3识别为HTML内容
  5. files: 可选:附件,可以为多个或没有,将File对象加在最后一个可变参数中即可

# 其它

  1. 自定义邮件服务器

除了使用配置文件定义全局账号以外,MailUtil.send方法同时提供重载方法可以传入一个MailAccount对象,这个对象为一个普通Bean,记录了邮件服务器信息。

MailAccount account = new MailAccount();
account.setHost("smtp.yeah.net");
account.setPort("25");
account.setAuth(true);
account.setFrom("hutool@yeah.net");
account.setUser("hutool");
account.setPass("q1w2e3");

MailUtil.send(account, CollUtil.newArrayList("hutool@foxmail.com"), "测试", "邮件来自Hutool测试", false);
  1. 使用SSL加密方式发送邮件 在使用QQ或Gmail邮箱时,需要强制开启SSL支持,此时我们只需修改配置文件即可:
# 发件人(必须正确,否则发送失败),“小磊”可以任意变更,<>内的地址必须唯一,以下方式也对
# from = hutool@yeah.net
from = 小磊<hutool@yeah.net>
# 密码(注意,某些邮箱需要为SMTP服务单独设置密码,详情查看相关帮助)
pass = q1w2e3
# 使用SSL安全连接
sslEnable = true

在原先极简配置下只需加入sslEnable即可完成SSL连接,当然,这是最简单的配置,很多参数根据已有参数已设置为默认。

完整的配置文件如下:

# 邮件服务器的SMTP地址
host = smtp.yeah.net
# 邮件服务器的SMTP端口
port = 465
# 发件人(必须正确,否则发送失败)
from = hutool@yeah.net
# 用户名(注意:如果使用foxmail邮箱,此处user为qq号)
user = hutool
# 密码(注意,某些邮箱需要为SMTP服务单独设置密码,详情查看相关帮助)
pass = q1w2e3
#使用 STARTTLS安全连接,STARTTLS是对纯文本通信协议的扩展。
starttlsEnable = true

# 使用SSL安全连接
sslEnable = true
# 指定实现javax.net.SocketFactory接口的类的名称,这个类将被用于创建SMTP的套接字
socketFactoryClass = javax.net.ssl.SSLSocketFactory
# 如果设置为true,未能创建一个套接字使用指定的套接字工厂类将导致使用java.net.Socket创建的套接字类, 默认值为true
socketFactoryFallback = true
# 指定的端口连接到在使用指定的套接字工厂。如果没有设置,将使用默认端口456
socketFactoryPort = 465

# SMTP超时时长,单位毫秒,缺省值不超时
timeout = 0
# Socket连接超时值,单位毫秒,缺省值不超时
connectionTimeout = 0
  1. 针对QQ邮箱和Foxmail邮箱的说明

(1) QQ邮箱中SMTP密码是单独生成的授权码,而非你的QQ密码,至于怎么生成,见腾讯的帮助说明:http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256 (opens new window)

使用帮助引导生成授权码后,配置如下即可:

pass = 你生成的授权码

(2) Foxmail邮箱本质上也是QQ邮箱的一种别名,你可以在你的QQ邮箱中设置一个foxmail邮箱,不过配置上有所区别。在Hutool中user属性默认提取你邮箱@前面的部分,但是foxmail邮箱是无效的,需要单独配置为与之绑定的qq号码或者XXXX@qq.com的XXXX。即:

host = smtp.qq.com
from = XXXX@foxmail.com
user = foxmail邮箱对应的QQ号码或者qq邮箱@前面部分
...

(3) 阿里云邮箱的user是邮箱的完整地址,即xxx@aliyun.com

  1. 针对QQ邮箱(foxmail)PKIX path building failed错误(since 5.6.4)

部分用户反馈发送邮件时会遇到错误:

cn.hutool.extra.mail.MailException: MessagingException: Could not connect to SMTP host: smtp.qq.com, port: 465
...
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

这个错误可能是需要SSL验证造成的,我们可以手动跳过这个验证:

MailAccount mailAccount = new MailAccount();
mailAccount.setAuth(true);
mailAccount.setSslEnable(true);
...
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
mailAccount.setCustomProperty("mail.smtp.ssl.socketFactory", sf);

Mail mail = Mail.create(mailAccount)
    .setTos("xx@xx.com")
	.setTitle("邮箱验证")
	.setContent("您的验证码是:<h3>2333</h3>")
	.setHtml(true)
	.send();
上次更新: 2023/05/08, 01:55:50
二维码工具-QrCodeUtil
Cglib工具-CglibUtil

← 二维码工具-QrCodeUtil Cglib工具-CglibUtil→

Theme by Vdoing | Copyright © 2023-2023 Hutool | MulanPSL-2.0
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式