admin管理员组

文章数量:1558996

需求

商户审核状态需要异步发送短信、站内通知和发送邮件通知商户,且发送账户限定为腾讯企业微信邮箱

准备

  1. 准备发送邮箱的账户和密码写入配置文件
  2. 引入发送邮箱jar包
  3. 写异步线程发送固定html格式的邮件

实现代码

配置文件

mail:
  transport:
    protocol: ssl
  smtp:
    host: smtp.exmail.qq # 企业微信的host
    port: 465
    auth: true
    ssl:
      enable : true
  enable: true
  account: 企业邮箱账户
  password: 企业邮箱密码

引入发送邮箱jar包

<dependency>
<groupid>com.sun.mailgroupid>
<artifactid>jakarta.mailartifactid>
<version>1.6.7version>
dependency>

代码块
定义一个接口:isendemailservice

import java.util.list;
public interface isendemailservice{
    /**
     * 发送邮件
     * @param fromaliasname 别名
     * @param to 发送目标
     * @param subject 主题
     * @param content 内容
     * @param attachfilelist 附件
     */
   void send(string fromaliasname,string to,string subject,string content, list<string> attachfilelist);
}

接口实现类:sendemailserviceimpl

/**
 * 邮件发送工具类
 * 注:腾讯企业微信邮箱需要用ssl方式发送
 */
@slf4j
@service
public class sendemailserviceimpl implements isendemailservice{
    @value("${mail.account}")
    private  string account ;
    /**
     * 登录密码
     */
    @value("${mail.password}")
    private  string password;
    /**
     * 发信协议
     */
    @value("${mail.transport.protocol}")
    private string protocol;
    /**
     * 邮件服务器地址
     */
    @value("${mail.smtp.host}")
    private string host;
    /**
     * 发信端口
     */
    @value("${mail.smtp.port}")
    private string port ;
    /**
     * 发信端口
     */
    @value("${mail.smtp.auth}")
    private string auth ;
    @value("${mail.smtp.ssl.enable}")
    private string sslenable ;
    /**
     * 发送邮件
     */
    @override
    @async(value = executorconfig.email_async)
    public void send(string fromaliasname,string to,string subject,string content,list<string> attachfilelist) {
        // 设置邮件属性
        properties prop = new properties();
        prop.setproperty("mail.transport.protocol", protocol);
        prop.setproperty("mail.smtp.host", host);
        prop.setproperty("mail.smtp.port", port);
        prop.setproperty("mail.smtp.auth", auth);
        mailsslsocketfactory sslsocketfactory = null;
        try {
            sslsocketfactory = new mailsslsocketfactory();
            sslsocketfactory.settrustallhosts(true);
        } catch (generalsecurityexception e1) {
            e1.printstacktrace();
        }
        if (sslsocketfactory == null) {
            log.error("开启 mailsslsocketfactory 失败");
        } else {
            prop.put("mail.smtp.ssl.enable",sslenable);
            prop.put("mail.smtp.ssl.socketfactory", sslsocketfactory);
            // 创建邮件会话(注意,如果要在一个进程中切换多个邮箱账号发信,应该用 session.getinstance)
            session session = session.getdefaultinstance(prop, new myauthenticator(account, password));
            try {
                mimemessage mimemessage = new mimemessage(session);
                // 设置发件人别名(如果未设置别名就默认为发件人邮箱)
                if (fromaliasname != null && !fromaliasname.trim().isempty()) {
                    mimemessage.setfrom(new internetaddress(account, fromaliasname));
                }
                // 设置主题和收件人、发信时间等信息
                mimemessage.addrecipient(message.recipienttype.to, new internetaddress(to));
                mimemessage.setsubject(subject);
                mimemessage.setsentdate(new date());
                // 如果有附件信息,则添加附件
                multipart multipart = new mimemultipart();
                mimebodypart body = new mimebodypart();
                body.setcontent(content, "text/html; charset=utf-8");
                multipart.addbodypart(body);
                // 添加所有附件(添加时判断文件是否存在)
                if (collectionutils.isnotempty(attachfilelist)){
                    for(string filepath : attachfilelist){
                        if(files.exists(paths.get(filepath))){
                            mimebodypart tempbodypart = new mimebodypart();
                            tempbodypart.attachfile(filepath);
                            multipart.addbodypart(tempbodypart);
                        }
                    }
                }
                mimemessage.setcontent(multipart);
                // 开始发信
                mimemessage.savechanges();
                transport.send(mimemessage);
            }catch (exception e) {
                log.error("发送邮件错误:{}",e.getmessage());
            }
        }
    }
    /**
     * 认证信息
     */
    static class myauthenticator extends authenticator {
        /**
         * 用户名
         */
        string username = null;
        /**
         * 密码
         */
        string password = null;
        /**
         * 构造器
         *
         * @param username 用户名
         * @param password 密码
         */
        public myauthenticator(string username, string password) {
            this.username = username;
            this.password = password;
        }
        @override
        protected passwordauthentication getpasswordauthentication() {
            return new passwordauthentication(username, password);
        }
    }
}

异步线程池配置


import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.scheduling.annotation.enableasync;
import org.springframework.scheduling.concurrent.threadpooltaskexecutor;
import java.util.concurrent.executor;
import java.util.concurrent.threadpoolexecutor;
@configuration
@enableasync
public class executorconfig{
    private int corepoolsize = 10;
    private int maxpoolsize = 50;
    private int queuecapacity = 100;
    /**
     * 邮件相关的异步
     */
    public static final string email_async="emailasync";

    @bean
    public executor emailasync(){
        threadpooltaskexecutor executor = new threadpooltaskexecutor();
        executor.setcorepoolsize(corepoolsize);
        executor.setmaxpoolsize(maxpoolsize);
        executor.setqueuecapacity(queuecapacity);
        executor.setthreadnameprefix(email_async);
        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // caller_runs:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setrejectedexecutionhandler(new threadpoolexecutor.callerrunspolicy());
        executor.initialize();
        return executor;
    }
}

调用方式

@restcontroller
@allargsconstructor
public class sendemailcontroller {
    @autowired
    private isendemailservice sendemailservice;
    /**
     * 发送邮件
     */
    @getmapping("/sendmail")
    @apioperationsupport(order = 1)
    @apioperation(value = "发送邮件")
    public void 发送sendmail() {
    	sendemailservice.send("别名","邮件","【审核通过】","内容","附件");
    }

结果

本文标签: 腾讯发送邮件邮箱企业springboot