zoukankan      html  css  js  c++  java
  • EmailService

    package me.zhengjie.tools.service;
    
    import me.zhengjie.tools.domain.EmailConfig;
    import me.zhengjie.tools.domain.vo.EmailVo;
    import org.springframework.cache.annotation.CacheConfig;
    import org.springframework.cache.annotation.CachePut;
    import org.springframework.cache.annotation.Cacheable;
    import org.springframework.scheduling.annotation.Async;
    
    /**
     * @author jie
     * @date 2018-12-26
     */
    @CacheConfig(cacheNames = "email")
    public interface EmailService {
    
        /**
         * 更新邮件配置
         * @param emailConfig
         * @param old
         * @return
         */
        @CachePut(key = "'1'")
        EmailConfig update(EmailConfig emailConfig, EmailConfig old);
    
        /**
         * 查询配置
         * @return
         */
        @Cacheable(key = "'1'")
        EmailConfig find();
    
        /**
         * 发送邮件
         * @param emailVo
         * @param emailConfig
         * @throws Exception
         */
        @Async
        void send(EmailVo emailVo, EmailConfig emailConfig) throws Exception;
    }
    package me.zhengjie.tools.service.impl;
    
    import cn.hutool.extra.mail.MailAccount;
    import cn.hutool.extra.mail.MailUtil;
    import me.zhengjie.common.exception.BadRequestException;
    import me.zhengjie.common.utils.ElAdminConstant;
    import me.zhengjie.core.utils.EncryptUtils;
    import me.zhengjie.tools.domain.EmailConfig;
    import me.zhengjie.tools.domain.vo.EmailVo;
    import me.zhengjie.tools.repository.EmailRepository;
    import me.zhengjie.tools.service.EmailService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Propagation;
    import org.springframework.transaction.annotation.Transactional;
    import java.util.Optional;
    
    /**
     * @author jie
     * @date 2018-12-26
     */
    @Service
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
    public class EmailServiceImpl implements EmailService {
    
        @Autowired
        private EmailRepository emailRepository;
    
        @Override
        @Transactional(rollbackFor = Exception.class)
        public EmailConfig update(EmailConfig emailConfig, EmailConfig old) {
            try {
                if(!emailConfig.getPass().equals(old.getPass())){
                    // 对称加密
                    emailConfig.setPass(EncryptUtils.desEncrypt(emailConfig.getPass()));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            emailRepository.saveAndFlush(emailConfig);
            return emailConfig;
        }
    
        @Override
        public EmailConfig find() {
            Optional<EmailConfig> emailConfig = emailRepository.findById(1L);
            if(emailConfig.isPresent()){
                return emailConfig.get();
            } else {
                return new EmailConfig();
            }
        }
    
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void send(EmailVo emailVo, EmailConfig emailConfig){
            if(emailConfig == null){
                throw new BadRequestException("请先配置,再操作");
            }
            /**
             * 封装
             */
            MailAccount account = new MailAccount();
            account.setHost(emailConfig.getHost());
            account.setPort(Integer.parseInt(emailConfig.getPort()));
            account.setAuth(true);
            try {
                // 对称解密
                account.setPass(EncryptUtils.desDecrypt(emailConfig.getPass()));
            } catch (Exception e) {
                throw new BadRequestException(e.getMessage());
            }
            account.setFrom(emailConfig.getUser()+"<"+emailConfig.getFromUser()+">");
            //ssl方式发送
            account.setStartttlsEnable(true);
            String content = emailVo.getContent()+ ElAdminConstant.EMAIL_CONTENT;
            /**
             * 发送
             */
            try {
                MailUtil.send(account,
                              emailVo.getTos(),
                              emailVo.getSubject(),
                              content,
                              true);
            }catch (Exception e){
                throw new BadRequestException(e.getMessage());
            }
        }
    }
    package me.zhengjie.tools.domain.vo;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    import javax.validation.constraints.NotBlank;
    import javax.validation.constraints.NotEmpty;
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * 发送邮件时,接收参数的类
     * @author 郑杰
     * @date 2018/09/28 12:02:14
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class EmailVo {
    
        /**
         * 收件人,支持多个收件人,用逗号分隔
         */
        @NotEmpty
        private List<String> tos;
    
        @NotBlank
        private String subject;
    
        @NotBlank
        private String content;
    }
    package me.zhengjie.tools.domain;
    
    import lombok.Data;
    import javax.persistence.*;
    import javax.validation.constraints.NotBlank;
    import java.io.Serializable;
    
    /**
     * 邮件配置类,数据存覆盖式存入数据存
     * @author jie
     * @date 2018-12-26
     */
    @Entity
    @Data
    @Table(name = "email_config")
    public class EmailConfig implements Serializable {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
    
        /**
         *邮件服务器SMTP地址
         */
        @NotBlank
        private String host;
    
        /**
         * 邮件服务器SMTP端口
         */
        @NotBlank
        private String port;
    
        /**
         * 发件者用户名,默认为发件人邮箱前缀
         */
        @NotBlank
        private String user;
    
        @NotBlank
        private String pass;
    
        /**
         * 发件人
         */
        @NotBlank
        private String fromUser;
    }
    package me.zhengjie.common.utils;
    
    /**
     * 常用静态常量
     * @author jie
     * @date 2018-12-26
     */
    public class ElAdminConstant {
    
        public static final String RESET_PASS = "重置密码";
    
        public static final String RESET_MAIL = "重置邮箱";
    
        public static final String EMAIL_CODE = "<p>你的验证码为:";
    
        public static final String EMAIL_CONTENT = "<p style='text-align: right;'>----- 邮件来自<span style='color: rgb(194, 79, 74);'>&nbsp;<a href='http://auauz.net' target='_blank'>eladmin</a></span>&nbsp;后台管理系统,系统邮件请勿回复</p>";
    
        /**
         * 常用接口
         */
        public static class Url{
            public static final String SM_MS_URL = "https://sm.ms/api/upload";
        }
    }
    package me.zhengjie.tools.rest;
    
    import lombok.extern.slf4j.Slf4j;
    import me.zhengjie.common.aop.log.Log;
    import me.zhengjie.tools.domain.EmailConfig;
    import me.zhengjie.tools.domain.vo.EmailVo;
    import me.zhengjie.tools.service.EmailService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.security.access.prepost.PreAuthorize;
    import org.springframework.validation.annotation.Validated;
    import org.springframework.web.bind.annotation.*;
    
    /**
     * 发送邮件
     * @author 郑杰
     * @date 2018/09/28 6:55:53
     */
    @Slf4j
    @RestController
    @RequestMapping("api")
    public class EmailController {
    
        @Autowired
        private EmailService emailService;
    
        @GetMapping(value = "/email")
        public ResponseEntity get(){
            return new ResponseEntity(emailService.find(),HttpStatus.OK);
        }
    
        @Log(description = "配置邮件")
        @PutMapping(value = "/email")
        public ResponseEntity emailConfig(@Validated @RequestBody EmailConfig emailConfig){
            emailService.update(emailConfig,emailService.find());
            return new ResponseEntity(HttpStatus.OK);
        }
    
        @Log(description = "发送邮件")
        @PostMapping(value = "/email")
        public ResponseEntity send(@Validated @RequestBody EmailVo emailVo) throws Exception {
            log.warn("REST request to send Email : {}" +emailVo);
            emailService.send(emailVo,emailService.find());
            return new ResponseEntity(HttpStatus.OK);
        }
    }
    package me.zhengjie.tools.repository;
    
    import me.zhengjie.tools.domain.EmailConfig;
    import org.springframework.data.jpa.repository.JpaRepository;
    
    /**
     * @author jie
     * @date 2018-12-26
     */
    public interface EmailRepository extends JpaRepository<EmailConfig,Long> {
    }
  • 相关阅读:
    第三节 单因素方差分析
    第四十一节 ORM介绍和用元类实现
    第四十节 通过type创建复杂的类,元类应用
    第二节 检验方法使用条件考察
    HDFS HA误删namenode后报错Nameservice testCluster has no SecondaryNameNode or High-Availability partner的恢复
    spark sql cache时发现的空字符串问题
    centos7环境下ELK部署之elasticsearch
    CDH升级 5.7.5 --> 5.13.3(tar包方式)
    CDH部署(以5.7.5为例)
    人生苦短,Let's Go
  • 原文地址:https://www.cnblogs.com/tonggc1668/p/11220375.html
Copyright © 2011-2022 走看看