JAVA SpringBoot 使用 hutool 工具实现发送邮件功能

官方文档  邮件工具-MailUtil (hutool.cn)icon-default.png?t=N7T8https://hutool.cn/docs/#/extra/%E9%82%AE%E4%BB%B6%E5%B7%A5%E5%85%B7-MailUtil

引入hutool包

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.12</version>
        </dependency>

引入发送邮件工具包

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

开启邮箱SMTP服务,获取授权码,授权码只显示一次,请保存后在关闭授权码窗口

发送邮件测试


        MailAccount account = new MailAccount();
        account.setHost("smtp.qq.com");//邮件服务器的SMTP地址,网易邮箱为smtp.163.com
        account.setPort(587);//邮件服务器的SMTP端口,QQ邮箱为465或587,网易邮箱为25
        account.setAuth(true);
        account.setFrom("xxxxxxxxxx@qq.com");//设置发送人邮箱
        account.setUser("xxxxxxxxxx");//发送人用户名
        account.setPass("xxxxxxxxxxxxxxxx");//密码或者授权码
        account.isSslEnable();//部分邮箱需要开启SSL
        /**
          使用SSL加密方式发送邮件 在使用QQ或Gmail邮箱时,需要强制开启SSL支持
        **/
 
        MailUtil.send(account, "xxxxxxxxxx@qq.com", //接收人邮箱
                "测试主题", "TEST", false);

以下是封装后的代码(以qq邮箱为例)


import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;

import java.io.File;
public class SendMail {
    private static final MailAccount account=new MailAccount();
    /***
     * receiverMail 接收人邮箱 ,也可以将String参数设置成集合如List<String>,
     * List<String>中存储多个邮箱地址,可以实现批量发送邮件
     * theme 发送邮件的标题 ,
     * Text 发送邮件的文本内容,
     * isHtml 当isHtml为ture且Text文本内容为html格式代码,邮件会以网页格式呈现
     * files 发送附件,可以发送多个附件,files可以为空,默认没有附件发送
     */
    public static void sendQQMail(String receiverMail, String theme,
                                  String Text, Boolean isHtml,File... files){
        account.setHost("smtp.qq.com");
        account.setPort(587);
        account.setAuth(true);
        account.setFrom("xxxxxxxxxx@qq.com");
        account.setUser("xxxxxxxxxx");
        account.setPass("xxxxxxxxxxxxxxxx");
        account.isSslEnable();
        //使用SSL加密方式发送邮件 在使用QQ或Gmail邮箱时,需要强制开启SSL支持
        MailUtil.send(account, receiverMail, theme, Text, isHtml,files);
    }
}

 测试

    @Test
    public void sendMail() {
        SendMail.sendQQMail("xxxxxxxxxx@qq.com","测试主题","TEST",false);
    }

接收成功

 SpringBoot配置文件

# 邮件服务器的SMTP地址
host = smtp.qq.net
# 邮件服务器的SMTP端口
port = 465
# 发件人(必须正确,否则发送失败)
from = xxxxxxl@qq.com
# 用户名(注意:如果使用foxmail邮箱,此处user为qq号)
user = xxxxxx
# 密码(注意,某些邮箱需要为SMTP服务单独设置密码,详情查看相关帮助)
pass =xxxxxx
#使用 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

或者配置mail.setting

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

属性

  1. tos: 对方的邮箱地址,可以是单个,也可以是多个(Collection表示)
  2. subject:标题
  3. content:邮件正文,可以是文本,也可以是HTML内容
  4. isHtml: 是否为HTML,如果是,那参数3识别为HTML内容
  5. files: 可选:附件,可以为多个或没有,将File对象加在最后一个可变参数中即可
/* * JCatalog Project */ package com.hexiang.utils; import java.util.List; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.Properties; import javax.mail.Session; import javax.mail.Transport; import javax.mail.Message; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.hexiang.exception.CatalogException; /** * Utility class to send email. * * @author <a href="380595305@qq.com">hexiang</a> */ public class EmailUtil { //the logger for this class private static Log logger = LogFactory.getLog("com.hexiang.util.EmailUtil"); /** * Send email to a single recipient. * * @param smtpHost the SMTP email server address * @param senderAddress the sender email address * @param senderName the sender name * @param receiverAddress the recipient email address * @param sub the subject of the email * @param msg the message content of the email */ public static void sendEmail(String smtpHost, String senderAddress, String senderName, String receiverAddress, String sub, String msg) throws CatalogException { List<String> recipients = new ArrayList<String>(); recipients.add(receiverAddress); sendEmail(smtpHost, senderAddress, senderName, recipients, sub, msg); } /** * Send email to a list of recipients. * * @param smtpHost the SMTP email server address * @param senderAddress the sender email address * @param senderName the sender name * @param recipients a list of receipients email addresses * @param sub the subject of the email * @param msg the message content of the email */ public static void sendEmail(String smtpHost, String senderAddress, String senderName, List<String> recipients, String sub, String msg) throws CatalogException { if (smtpHost == null) { String errMsg = "Could not send email: smtp host address is null"; logger.error(errMsg); throw new CatalogException(errMsg); } try { Properties props = System.getProperties(); props.put("mail.smtp.host", smtpHost); Session session = Session.getDefaultInstance(props, null ); MimeMessage message = new MimeMessage( session ); message.addHeader("Content-type", "text/plain"); message.setSubject(sub); message.setFrom(new InternetAddress(senderAddress, senderName)); for (Iterator<String> it = recipients.iterator(); it.hasNext();) { String email = (String)it.next(); message.addRecipients(Message.RecipientType.TO, email); } message.setText(msg); message.setSentDate( new Date() ); Transport.send(message); } catch (Exception e) { String errorMsg = "Could not send email"; logger.error(errorMsg, e); throw new CatalogException("errorMsg", e); } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值