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. Day 9:双列集合Map及实现该接口的类的常用方法

    为什么要学双列集合? 因为单列集合无法处理映射关系,会有成对出现的数据 Map接口  如果是实现了Map接口的集合类,具备的特点: 存储的数据都是以键值对的形式存在的,键不可重复,值可以重复 Map接 ...

  2. POJ 3438:Look and Say

    Look and Say Time Limit: 5000MS   Memory Limit: 65536K Total Submissions: 9196   Accepted: 5566 Desc ...

  3. java基础二 分支循环

    分支循环:    if...    if...else...    if...else if...    if...else if...else...    switch...case...defau ...

  4. MySQL硬核干货:从磁盘读取数据页到缓冲池时,免费链表有什么用?

    1.数据库启动的时候,是如何初始化Buffer Pool的? 现在我们已经搞明白一件事儿了,那就是数据库的Buffer Pool到底长成个什么样,大家想必都是理解了 其实说白了,里面就是会包含很多个缓 ...

  5. OGG实验:喂奶间隔数据表通过OGG配置同步

    我之前在<使用SQL计算宝宝每次吃奶的时间间隔(数据保障篇)>中提到数据实时同步的方案,其中有一种是数据表通过OGG进行同步,当时没有详细展开测试,只给了之前学习OGG时的配置示例.由于之 ...

  6. eclipse导入tomcat源码

    我的开发环境:windows7  64位 一.官网下载tomcat源码.在此奉上一站地址:http://archive.apache.org/dist/tomcat/: 二.编译源码生成.jar文件: ...

  7. Vue.js 之 过渡动画

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  8. iOS 中的延时操作方法

    1. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_q ...

  9. kafka 零拷贝

    kafka通过零拷贝实现高效的数据传输 https://blog.csdn.net/lxlmycsdnfree/article/details/78973864 Kafka零拷贝 https://bl ...

  10. ZJNU 2345 - 小Y的方格纸

    明显,总共有n*m格,已经涂了k格 所以剩下n*m-k格 如果n*m-k<=k,即k已经占用了大于等于一半的格子,显然答案为0 否则 剩下的格子中取k+1,k+2...n*m-k格均可 取组合数 ...