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> {
}

EmailService的更多相关文章

  1. Configuring Autofac to work with the ASP.NET Identity Framework in MVC 5

    https://developingsoftware.com/configuring-autofac-to-work-with-the-aspnet-identity-framework-in-mvc ...

  2. .NET单元测试的艺术-2.核心技术

    开篇:上一篇我们学习基本的单元测试基础知识和入门实例.但是,如果我们要测试的方法依赖于一个外部资源,如文件系统.数据库.Web服务或者其他难以控制的东西,那又该如何编写测试呢?为了解决这些问题,我们需 ...

  3. Windows Service--Write a Better Windows Service

    原文地址: http://visualstudiomagazine.com/Articles/2005/10/01/Write-a-Better-Windows-Service.aspx?Page=1 ...

  4. SpringBoot应用部署[转]

    在开发spring Boot应用的过程中,Spring Boot直接执行public static void main()函数并启动一个内嵌的应用服务器(取决于类路径上的以来是Tomcat还是jett ...

  5. 依赖注入 – ASP.NET MVC 4 系列

           从 ASP.NET MVC 3.0 开始就引入了一个新概念:依赖解析器(dependence resolver).极大的增强了应用程序参与依赖注入的能力,更好的在 MVC 使用的服务和创 ...

  6. springMVC发送邮件

    springMVC发送邮件 利用javax.mail发送邮件,图片与附件都可发送 1,Controller类 package com.web.controller.api; import javax. ...

  7. MVC使用ASP.NET Identity 2.0实现用户身份安全相关功能,比如通过短信或邮件发送安全码,账户锁定等

    本文体验在MVC中使用ASP.NET Identity 2.0,体验与用户身份安全有关的功能: →install-package Microsoft.AspNet.Identity.Samples - ...

  8. AspNet Identity and IoC Container Registration

    https://github.com/trailmax/IoCIdentitySample TL;DR: Registration code for Autofac, for SimpleInject ...

  9. spring 部分配置内容备忘

    1.spring定时器简单配置: <bean name="taskJob" class="com.netcloud.mail.util.TaskJob"& ...

随机推荐

  1. 程序员:java中直接或间接创建线程的方法总结

    在java开发中,经常会涉及多线程的编码,那么通过直接或间接创建线程的方法有哪些?现整理如下: 1.继承Thread类,重写run()方法 class Worker extends Thread { ...

  2. POJ 2006:Litmus Test 化学公式

    Litmus Test Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 1709   Accepted: 897 Descri ...

  3. 在设备上启用 adb 调试,有一个小秘密

    要在通过 USB 连接的设备上使用 adb,您必须在设备的系统设置中启用 USB 调试(位于开发者选项下). 在搭载 Android 4.2 及更高版本的设备上,“开发者选项”屏幕默认情况下处于隐藏状 ...

  4. JS-表单非空验证

    JavaScript 表单验证 JavaScript 可用来在数据被送往服务器前对 HTML 表单中的这些输入数据进行验证. 实例:1.用户名的非空验证代码如下: <head> <m ...

  5. HTML超链接实例介绍

    <html><head><title>第六节课</title><meta charset="UTF-8"></he ...

  6. 深入JVM(一)JVM指令手册

    本文按照如下思维导图组织 1. 栈和局部变量操作 1.1 将常量压入栈的指令 aconst_null 将null对象引用压入栈iconst_m1 将int类型常量-1压入栈iconst_0 将int类 ...

  7. STM32重映射

  8. Spring DATA Neo4J(一)

    Spring DATA Neo4J——简介 Spring Framework提供了一下模块来处理基于Java的应用程序的DAO层 Spring JDBC Spring ORM Spring DATA ...

  9. [C/C++]C/C++计算代码的运行时间

    有很多时候,实现一个功能后可能不仅仅要效果,还要效率,如果可以在极短的时间内完成一个功能那当然是最好不过的啦,但是可能经常会事与愿违. 这里就写一下,都可以怎样用C/C++或者Qt的方法来测试代码的运 ...

  10. openlayers的loaders方式加载

    openlayers loaders方式加载 let layerVector = new ol.layer.Vector({ source : new ol.source.Vector({ loade ...