Commit 696c4a96 authored by 吴琼's avatar 吴琼

发送邮件

parent 6f24e5cd
......@@ -330,6 +330,10 @@
<artifactId>hutool-all</artifactId>
<version>5.4.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
</dependencies>
</project>
......@@ -10,6 +10,7 @@ import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.context.annotation.Import;
import org.springframework.jmx.support.RegistrationPolicy;
import org.springframework.scheduling.annotation.EnableAsync;
@Import(FdfsClientConfig.class)
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
......@@ -17,6 +18,7 @@ import org.springframework.jmx.support.RegistrationPolicy;
@ServletComponentScan
@EnableAspectJAutoProxy
@EnableApolloConfig
@EnableAsync
@SpringBootApplication(scanBasePackages = {"cn.quantgroup.customer"})
public class Bootstrap {
......
package cn.quantgroup.customer.config.mail;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import java.util.Properties;
/**
* @author jie.feng
*/
@Configuration
public class MailConfig {
@Value("${customer.transaction.mail.from}")
private String username;
@Value("${customer.transaction.mail.host}")
private String host;
@Value("${customer.transaction.mail.port}")
private int port = 587;
@Value("${customer.transaction.mail.password}")
private String password;
@Bean(name = "monitorMailSender")
public JavaMailSender getSender() {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setUsername(username);
javaMailSender.setHost(host);
javaMailSender.setPort(port);
javaMailSender.setDefaultEncoding("UTF-8");
javaMailSender.setPassword(password);
Properties prop = new Properties();
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.timeout", "25000");
prop.setProperty("mail.smtp.port", Integer.toString(port));
//设置ssl端口
prop.setProperty("mail.smtp.socketFactory.port", Integer.toString(port));
prop.setProperty("mail.smtp.socketFactory.fallback", "false");
prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
javaMailSender.setJavaMailProperties(prop);
return javaMailSender;
}
}
\ No newline at end of file
......@@ -10,6 +10,7 @@ import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
......@@ -88,7 +89,13 @@ public class TransactionReceiptRecordRest {
@ResponseBody
public JsonResult exportTransactionZipFile(HttpServletRequest request, HttpServletResponse response) throws Exception{
try{
return transactionReceiptRecordService.exportZipFile(request,response);
//transactionReceiptRecordService.deleteRedis("exportZipFile");
String str = transactionReceiptRecordService.checkRedis("exportZipFile");
if(StringUtils.isNotBlank(str)){
return JsonResult.buildErrorStateResult("正在处理中,请稍后查看邮箱");
}
transactionReceiptRecordService.exportZipFile(request,response);
return JsonResult.buildSuccessResult("请求已发送,请稍后查看邮箱",null);
}catch(Exception e){
transactionReceiptRecordService.deleteRedis("exportZipFile");
return JsonResult.buildErrorStateResult(e.getMessage());
......@@ -96,10 +103,20 @@ public class TransactionReceiptRecordRest {
}
@RequestMapping(value = "/redis", method = RequestMethod.GET)
public JsonResult redisTest() {
transactionReceiptRecordService.deleteRedis("exportZipFile");
return JsonResult.buildSuccessResult("删除成功",null);
@RequestMapping(value = "/orderQuery/checkRedis", method = RequestMethod.GET)
public JsonResult redisTest(String type) {
if(type.equals("1")){
String str = transactionReceiptRecordService.checkRedis("importTransactionReceiptRecord");
if(StringUtils.isNotBlank(str)){
return JsonResult.buildErrorStateResult("只能一个人导入,当前有其他人正在导入,请稍后重试");
}
}else{
String str = transactionReceiptRecordService.checkRedis("exportZipFile");
if(StringUtils.isNotBlank(str)){
return JsonResult.buildErrorStateResult("只能一个人导出,当前有其他人正在导出,请稍后重试");
}
}
return JsonResult.buildSuccessResult("ok",null);
}
}
package cn.quantgroup.customer.rest.param.mail;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.core.io.InputStreamSource;
import java.io.Serializable;
/**
* Desc :
* Date : 2017/9/28
* Created with suntao
*/
@Data
@NoArgsConstructor
public class SendMailParam implements Serializable {
private static final long serialVersionUID = -1L;
private String subject;
private String sender;
private String[] receiver;
private String[] copier;
private String contentText;
private String attachmentFileName;
private InputStreamSource inputStreamSource;
/**
* 简单邮件参数
* @param subject 主题
* @param sender 发件人
* @param receiver 收件人
* @param copier 抄送人
* @param contentText 内容
*/
public SendMailParam(String subject, String sender, String[] receiver, String[] copier, String contentText) {
this.subject = subject;
this.sender = sender;
this.receiver = receiver;
this.copier = copier;
this.contentText = contentText;
}
/**
* 附件邮件参数
* @param subject 主题
* @param sender 发件人
* @param receiver 收件人
* @param copier 抄送人
* @param contentText 内容
* @param attachmentFileName 附件名称
* @param inputStreamSource 附件流
*/
public SendMailParam(String subject, String sender, String[] receiver, String[] copier, String contentText, String attachmentFileName, InputStreamSource inputStreamSource) {
this.subject = subject;
this.sender = sender;
this.receiver = receiver;
this.copier = copier;
this.contentText = contentText;
this.attachmentFileName = attachmentFileName;
this.inputStreamSource = inputStreamSource;
}
}
......@@ -16,7 +16,7 @@ public interface ITransactionReceiptRecordService {
JsonResult importTransactionReceiptRecord(MultipartFile file) throws IOException;
JsonResult exportZipFile(HttpServletRequest request, HttpServletResponse response) throws Exception;
void exportZipFile(HttpServletRequest request, HttpServletResponse response) throws Exception;
JsonResult checkCanExport();
......@@ -26,4 +26,6 @@ public interface ITransactionReceiptRecordService {
void deleteRedis(String str);
String checkRedis(String str);
}
package cn.quantgroup.customer.util;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
*
* @author hang.zheng
*/
@Component
public class ApplicationContextHolder implements ApplicationContextAware {
@Autowired
public ApplicationContextHolder(ApplicationContext applicationContext) {
ApplicationContextHolder.applicationContext = applicationContext;
}
/**
* Spring应用上下文环境
*/
private static ApplicationContext applicationContext;
/**
* 实现ApplicationContextAware接口的回调方法,设置上下文环境.
*
* @param applicationContext Spring ApplicationContext上下文
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
ApplicationContextHolder.applicationContext = applicationContext;
}
/**
* 获取一个ApplicationContext.
*
* @return ApplicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 根据名称获取一个对象.
*
* @param name bean名称
* @return Object 指定的bean
* @throws BeansException 如果找不到bean
*/
public static <T> T getBean(String name) throws BeansException {
return (T) applicationContext.getBean(name);
}
/**
* 获取名称为name的bean,自动转为所需类型.
*
* @param <T> 需求的bean类型
* @param name bean名称
* @param requiredType 需求的bean类型
* @return 指定类型的bean
* @throws BeansException 如果找不到匹配的类型,或是类型不能被转换,或是bean实例化失败
*/
public static <T> T getBean(String name, Class<T> requiredType) throws BeansException {
return applicationContext.getBean(name, requiredType);
}
/**
* 获取类型为requiredType的对象.
*
* @param <T> 需求的bean类型
* @param requiredType 需求的bean类型
* @return 指定类型的bean
* @throws BeansException 如果找不到匹配的类型
*/
public static <T> T getBean(Class<T> requiredType) throws BeansException {
return applicationContext.getBean(requiredType);
}
/**
* 检测一个bean是否已经被定义.
*
* @param name bean名称
* @return boolean 如果bean已经被定义,则返回true,否则返回false
*/
public static boolean containsBean(String name) {
return applicationContext.containsBean(name);
}
/**
* 判断以给定名字注册的bean定义是一个singleton还是一个prototype.
*
* @param name bean名称
* @return boolean 如果是singleton则返回true
* @throws NoSuchBeanDefinitionException 如果bean名称不存在
*/
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
return applicationContext.isSingleton(name);
}
/**
* 获取给定名字的bean的类型.
*
* @param name bean名称
* @return Class bean类型
* @throws NoSuchBeanDefinitionException 如果bean名称不存在
*/
public static Class getType(String name) throws NoSuchBeanDefinitionException {
return applicationContext.getType(name);
}
/**
* 取出指定bean的别名列表.
*
* @param name bean名称
* @return 如果有别名,返回别名,否则返回空数组.
* @throws NoSuchBeanDefinitionException 如果bean名称不存在
*/
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
return applicationContext.getAliases(name);
}
}
\ No newline at end of file
package cn.quantgroup.customer.util;
import cn.quantgroup.customer.rest.param.mail.SendMailParam;
import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeUtility;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.mail.internet.MimeMessage;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import java.io.Serializable;
/**
* Date : 2017/9/28
* Created with suntao
*/
public class MailUtil implements Serializable {
private static final long serialVersionUID = -1L;
private static Logger logger = LoggerFactory.getLogger(MailUtil.class);
/**
* 发送一个简单邮件
*
* @param param
*/
public static void sendSampleMail(SendMailParam param) throws Exception {
if (!isSampleParamValidation(param)) {
return;
}
JavaMailSender mailSender = ApplicationContextHolder.getBean("monitorMailSender");
//SimpleMailMessages实现了MimeMessageHelper,为普通邮件模板,支持文本。
SimpleMailMessage smm = new SimpleMailMessage();
// 设定邮件参数
smm.setFrom(param.getSender());
smm.setTo(param.getReceiver());
if (ArrayUtils.isNotEmpty(param.getCopier())) {
smm.setCc(param.getCopier());
}
smm.setSubject(param.getSubject());
smm.setText(param.getContentText());
// 发送邮件
try {
mailSender.send(smm);
} catch (MailException e) {
logger.error("[MailUtilSendMail] 邮件发送失败。", e);
throw new Exception(e);
}
}
/**
* 发送一个支持html的邮件
*
* @param param Sender,Subject,Receiver,ContentText必选,Copier选填
*/
public static void sendHtmlMail(SendMailParam param) {
if (!isSampleParamValidation(param)) {
return;
}
JavaMailSender mailSender = ApplicationContextHolder.getBean("monitorMailSender");
MimeMessage mimeMessage;
try {
mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(param.getSender());
helper.setSubject(param.getSubject());
helper.setTo(param.getReceiver());
if (ArrayUtils.isNotEmpty(param.getCopier())) {
helper.setCc(param.getCopier());
}
helper.setText(param.getContentText(), Boolean.TRUE);
mailSender.send(mimeMessage);
} catch (Exception e) {
logger.error("[MailUtilSendMail] 邮件发送失败。", e);
}
}
/**
* 发送一个支持html 和 附件 的邮件
*
* @param param Sender,Subject,Receiver,ContentText,AttachmentFileName,Attachment必选,Copier选填
*/
public static void sendHtmlAndAttachmentMail(SendMailParam param) {
if (!isAttachmentParamValidation(param)) {
return;
}
JavaMailSender mailSender = ApplicationContextHolder.getBean("monitorMailSender");
MimeMessage mimeMessage;
try {
mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(param.getSender());
helper.setSubject(param.getSubject());
helper.setTo(param.getReceiver());
if (ArrayUtils.isNotEmpty(param.getCopier())) {
helper.setCc(param.getCopier());
}
helper.setText(param.getContentText(), Boolean.TRUE);
helper.addAttachment(MimeUtility.encodeWord(param.getAttachmentFileName()), new ByteArrayResource(IOUtils.toByteArray(param.getInputStreamSource().getInputStream())));
mailSender.send(mimeMessage);
} catch (Exception e) {
logger.error("[MailUtilSendMail] 邮件发送失败。", e);
}
}
/**
* 验证简单邮件参数
*
* @param param
* @return true:参数正确;false:参数有误
*/
private static boolean isSampleParamValidation(SendMailParam param) {
if (param == null) {
logger.error("[MailUtilSendMail] 邮件发送失败, 发送参数为空");
return false;
}
if (StringUtils.isAnyBlank(param.getSender(), param.getSubject(), param.getContentText()) || ArrayUtils.isEmpty(param.getReceiver())) {
logger.error("[MailUtilSendMail] 邮件发送失败, 请检查参数");
return false;
}
return true;
}
/**
* 验证附件邮件参数
*
* @param param
* @return true:参数正确;false:参数有误
*/
private static boolean isAttachmentParamValidation(SendMailParam param) {
if (param == null) {
logger.error("[MailUtilSendMail] 邮件发送失败, 发送参数为空");
return false;
}
if (StringUtils.isAnyBlank(param.getSender(), param.getSubject(), param.getContentText(),
param.getAttachmentFileName()) || ArrayUtils.isEmpty(param.getReceiver()) || param.getInputStreamSource() == null) {
logger.error("[MailUtilSendMail] 邮件发送失败, 请检查参数");
return false;
}
return true;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment