情景
:业务项目,异步调用公共模块项目,发送邮件、短信
实现步骤
:
1.业务项目组装入参调用邮件短信服务
1.1组装入参
sendEmail("",updateCaseInFoReqDto.getCASECODE(),"","","","","","",sdf.format(new Date()),"","",paUser.getEmail(),"reportNotMailType","reportNotMailName","reportNotMailTitle","reportNotMailParam");
//发送短信
sendMessage("","","","","","","","",updateCaseInFoReqDto.getCASECODE(),"","",paUser.getPhone(),"reportNotMsg");
1.2调用方法
public void sendMessage(String time,String reason,String refername,String orgname,String estimatorname,String password,String estimatorcode,String refercode,String casecode,String nowestimatorname,String nowestimatorcode,String APPLYTEL,String MSGTYPE){
//发送短信
Map<String,String> messageMap = new HashMap<String,String>();
if(!time.equals("")) messageMap.put("time",time); // 派工时间
if(!reason.equals("")) messageMap.put("reason",reason); // 原因
if(!refername.equals("")) messageMap.put("refername",refername); // 操作人
if(!orgname.equals("")) messageMap.put("orgname",orgname); //归属机构
if(!estimatorname.equals("")) messageMap.put("estimatorname",estimatorname);//申请人
if(!password.equals("")) messageMap.put("password",password);//密码
if(!estimatorcode.equals("")) messageMap.put("estimatorcode",estimatorcode);//申请人工号
if(!refercode.equals("")) messageMap.put("refercode",refercode); //工号
if(casecode == null || !casecode.equals("")) messageMap.put("casecode",casecode == null ? "" :casecode); //案件编号casecode
if(!nowestimatorname.equals("")) messageMap.put("nowestimatorname",nowestimatorname); //现指派人
if(!nowestimatorcode.equals("")) messageMap.put("nowestimatorcode",nowestimatorcode); //现指派人工号
if(!APPLYTEL.equals("")) messageMap.put("APPLYTEL",APPLYTEL); //手机号
if(!MSGTYPE.equals("")) messageMap.put("MSGTYPE",MSGTYPE); //短信类型
logger.info("发送短信信息:"+JSON.toJSONString(messageMap));
notificationManageSend.sendMessage(JSON.toJSONString(messageMap));
//String messageString = selectCommonInFoFeignClient.sendMessage(JSON.toJSONString(messageMap));
}
public void sendEmail(String REASON,String CASENUMBER,String REFERNAME,String REFERCODE,String USERNAME,String ORGANSNAME,String USERCODE,String PASSWORD,String SENDTIME,String OWNERNAME,String OWNERCODE,String email,String mailTemplateType,String senderMailName,String mailTitleType,String mailParamType){
//发送邮件CASENUMBER
Map<String,String> emailMap = new HashMap<String,String>();
if(!REASON.equals("")) emailMap.put("REASON",REASON); //注销原因
if(CASENUMBER == null || !CASENUMBER.equals("")) emailMap.put("CASENUMBER",CASENUMBER == null ? "无" : CASENUMBER); //案件编号
//案件编号无邮件发送不出去
if(CASENUMBER == null || CASENUMBER.equals("")){
emailMap.put("CASENUMBER","无"); //案件编号
}else{
emailMap.put("CASENUMBER",CASENUMBER); //案件编号
}
if(!REFERNAME.equals("")) emailMap.put("REFERNAME",REFERNAME); //人,下面的操作人工号进行关联,某人向某人分配案件
if(!REFERCODE.equals("")) emailMap.put("REFERCODE",REFERCODE); //工号
if(!USERNAME.equals("")) emailMap.put("USERNAME",USERNAME); //操作人人
if(!ORGANSNAME.equals("")) emailMap.put("ORGANSNAME",ORGANSNAME); //归属机构
if(!USERCODE.equals("")) emailMap.put("USERCODE",USERCODE); //操作人工号
if(!PASSWORD.equals("")) emailMap.put("PASSWORD",PASSWORD); //密码
if(!SENDTIME.equals("")) emailMap.put("SENDTIME",SENDTIME); // 当前时间
if(!OWNERNAME.equals("")) emailMap.put("OWNERNAME",OWNERNAME); //现指派人
if(!OWNERCODE.equals("")) emailMap.put("OWNERCODE",OWNERCODE); // 现指派人
if(!email.equals("")) emailMap.put("email",email); //收件人邮箱
if(!mailTemplateType.equals("")) emailMap.put("mailTemplateType",mailTemplateType); //模板类型
if(!senderMailName.equals("")) emailMap.put("senderMailName",senderMailName); //邮件发件人姓名
if(!mailTitleType.equals("")) emailMap.put("mailTitleType",mailTitleType); //邮件主题
if(!mailParamType.equals("")) emailMap.put("mailParamType",mailParamType); //邮件参数
logger.info("发送邮件信息:"+JSON.toJSONString(emailMap));
notificationManageSend.sendEmail(JSON.toJSONString(emailMap));
//String emailString = selectCommonInFoFeignClient.senEmail(JSON.toJSONString(emailMap));
}
1.3异步调用公共模块发送邮件短信
注使用异步,需在启动类加入注解@EnableAsync、pom添加依赖,调用方法加入注解
```bash
@Service
@PropertySource("classpath:/content.properties")
public class NotificationManageSendImpl implements NotificationManageSend {
RestTemplate restTemplate = new RestTemplate();
@Value("${url}")
private String url;
@Value("${email}")
private String email;
@Value("${message}")
private String message;
@Override
@Async
public String sendEmail(String requestString){
String sendEmailUrl = url + email;
restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
return restTemplate.postForObject(sendEmailUrl, requestString,String.class);
}
@Override
@Async
public String sendMessage(String requestString){
String sendMessageUrl = url + message;
restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
return restTemplate.postForObject(sendMessageUrl, requestString,String.class);
}
}
2.公共模块项目执行发送邮件短信
2.1执行方法前,需要获取两部分配置信息
第一:数据库中配置邮件模板参数信息,一般是内容、参数、标题、发送方(上一章节写过),或者短信信息配置
第二:发送邮件所需要的第三方依赖配置信息(每个公司都有配置)
2.2发送邮件
```bash
@Service
@PropertySource(value="classpath:content.properties")
public class EmailSendServiceImpl implements EmailSendService {
private Logger logger = LoggerFactory.getLogger(EmailSendServiceImpl.class);
@Autowired
private StringRedisTemplate redisTemplate;
@Autowired
private RedisCacheServiceImpl redisCacheServiceImpl;
private String host = ""; // smtp服务器
//private String from = ""; // 发件人地址
//private String to = ""; // 收件人地址
private String affix = ""; // 附件地址
private String affixName = ""; // 附件名称
private String user = ""; // 用户名
private String pwd = ""; // 密码
//private String subject = ""; // 邮件标题
//private String content = ""; //邮件文本内容
private String myEmailName = "";//发件人别名
/* *
* @Description:获取邮件参数
* @Author: duyajun
* @Param: emailString
* @Return: String
*/
@Override
public void sendEmail(String emailString) {
//接口传送的数据
JSONObject prams = JSONObject.parseObject(emailString);
logger.info("接口邮件发送数据" + prams);
//此处从redis中取得金诚基础信息
// Map<String,Object> etibInfoMap = JSON.parseObject(redisTemplate.opsForValue().get("CLAIMS"),Map.class);
Map<String, Object> etibInfoMap = (Map<String, Object>) redisCacheServiceImpl.getCache("CLAIMS");
//Map<String, Object> etibInfoMap = (Map<String, Object>) redisCacheService.getCache("ETIB");
logger.info("获取的缓存数据Map:" + etibInfoMap.toString());
String receiveMailAccount = prams.getString("email");//收件人邮箱
logger.info("收件人邮箱:" + receiveMailAccount);
Map<String, String> senderMailAccount = (Map<String, String>) etibInfoMap.get("senderMailAccount");
String myEmailAccount = senderMailAccount.get("codeCode");//发件人邮箱账号
logger.info("发件人邮箱账号:" + myEmailAccount);
Map<String, String> senderMailName = (Map<String, String>) etibInfoMap.get(prams.getString("senderMailName"));
String myEmailName = senderMailName.get("codeCode");//发件人邮箱账号别名
Map<String, String> senderMailPwd = (Map<String, String>) etibInfoMap.get("senderMailPwd");
String myEmailPassword = senderMailPwd.get("codeCode");//发件人邮箱密码
Map<String, String> mailTitleType = (Map<String, String>) etibInfoMap.get(prams.getString("mailTitleType"));
String mailTitle = mailTitleType.get("codeCode");//邮件标题
Map<String, String> mailTemplateType = (Map<String, String>) etibInfoMap.get(prams.getString("mailTemplateType"));
String mailTemplate = mailTemplateType.get("codeCode");//邮件模板类型
logger.info("邮件模板:" + mailTemplate);
Map<String, String> mailParamType = (Map<String, String>) etibInfoMap.get(prams.getString("mailParamType"));
String mailParam = mailParamType.get("codeCode");//邮件参数
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String createTime = sdf.format(new Date());//创建时间
String[] mailParams = mailParam.split("\\,");
logger.info("邮件参数:" + mailParams);
//将模板参数封装成map
Map templateMap = new HashMap();
for (int i = 0; i < mailParams.length; i++) {
templateMap.put(mailParams[i], prams.getString(mailParams[i]));
}
templateMap.put("myEmailName", myEmailName);
templateMap.put("createTime", createTime);
logger.info("模板参数Map:" + templateMap);
//freemarker封装邮件内容
String mailContent = getMailText(templateMap, mailTemplate);
// 设置发件人地址、收件人地址、邮件标题和邮件内容
//setAddress(myEmailAccount, receiveMailAccount, mailTitle, mailContent);
// 设置要发送附件的位置和标题
//cn.setAffix("C:/Users/ETIB-SQ0017/Desktop/保险公司条款费率/客户告知书(总部适用).pdf", "客户告知书.pdf");
/**
* 设置smtp服务器以及邮箱的帐号和密码
* 用QQ 邮箱作为发生者不好使 (原因不明)
* 163 邮箱可以,但是必须开启 POP3/SMTP服务 和 IMAP/SMTP服务
* 因为程序属于第三方登录,所以登录密码必须使用163的授权码
*/
// 注意: [授权码和你平时登录的密码是不一样的]
String host = Constant.getProperties().getStringProperty("email.host");//邮件服务器的属性
send(host, myEmailAccount, myEmailPassword, myEmailName, myEmailAccount, receiveMailAccount, mailTitle, mailContent);
}
/* *
* @Description: 邮件的发件人 收件人 标题和各部分内容
* @Author: duyajun
* @Param: from to subject content
* @Return: String
*/
// @Override
// public void setAddress(String from, String to, String subject, String content) {
// this.from = from;
// this.to = to;
// this.subject = subject;
// this.content = content;
// }
@Override
public void setAffix(String affix, String affixName) {
this.affix = affix;
this.affixName = affixName;
}
@Override
public void send(String host, String user, String pwd, String myEmailName, String from, String to, String subject, String content) {
this.host = host;
this.user = user;
this.pwd = pwd;
this.myEmailName = myEmailName;
logger.info("密码:" + pwd);
Properties props = new Properties();
// 使用的协议(JavaMail规范要求)
props.setProperty("mail.transport.protocol", "smtp");
// 设置发送邮件的邮件服务器的属性(这里使用网易的smtp服务器)
props.put("mail.smtp.host", host);
// 需要经过授权,也就是用户名和密码的校验,这样才能通过验证(一定要有这一条)
props.put("mail.smtp.auth", "true");
// PS: 某些邮箱服务器要求 SMTP 连接需要使用 SSL 安全认证 (为了提高安全性, 邮箱支持SSL连接, 也可以自己开启),
// 如果无法连接邮件服务器, 仔细查看控制台打印的 log, 如果有有类似 “连接失败, 要求 SSL 安全连接” 等错误,
// 打开下面 /* ... */ 之间的注释代码, 开启 SSL 安全连接。
// SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加, 如果开启了 SSL 连接,
// 需要改为对应邮箱的 SMTP 服务器的端口, 具体可查看对应邮箱服务的帮助,
// QQ邮箱的SMTP(SLL)端口为465或587, 其他邮箱自行去查看)
final String smtpPort = "465";
props.setProperty("mail.smtp.port", smtpPort);
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.socketFactory.port", smtpPort);
// 用刚刚设置好的props对象构建一个session
Session session = Session.getDefaultInstance(props);
// 有了这句便可以在发送邮件的过程中在console处显示过程信息,供调试使
// 用(你可以在控制台(console)上看到发送邮件的过程)
session.setDebug(true);
// 用session为参数定义消息对象
MimeMessage message = new MimeMessage(session);
Transport transport = null;
try {
// 加载发件人地址
message.setFrom(new InternetAddress(from, myEmailName, "UTF-8"));
// 加载收件人地址
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// 加载标题
message.setSubject(subject, "UTF-8");
// 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
Multipart multipart = new MimeMultipart();
// 设置邮件的文本内容
BodyPart contentPart = new MimeBodyPart();
contentPart.setContent(content, "text/html;charset=UTF-8");
multipart.addBodyPart(contentPart);
// 将multipart对象放到message中
message.setContent(multipart);
// 保存邮件
message.saveChanges();
// 发送邮件
transport = session.getTransport("smtp");
// 连接服务器的邮箱
transport.connect(host, user, pwd);
// 把邮件发送出去
transport.sendMessage(message, message.getAllRecipients());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
/* *
* @Description: 获取模板以及模板解析输出处理,最后输出结果
* @Author: duyajun
* @Param: dataMap templateContent
* @Return: Map String
*/
private String getMailText(Map dataMap, String templateContent) {
String restring = "";
try {
//模板配置
Configuration cfg = new Configuration();
//字符串模板加载器
StringTemplateLoader stringLoader = new StringTemplateLoader();
stringLoader.putTemplate("templateName", templateContent);
cfg.setTemplateLoader(stringLoader);
//获取模板
Template template = cfg.getTemplate("templateName", "utf-8");
//模板解析输出
StringWriter writer = new StringWriter();
//执行模板解析处理
template.process(dataMap, writer);
//输出结果
restring=writer.toString();
writer.close();
System.out.println(restring);
return restring;
} catch (Exception e) {
e.printStackTrace();
}
return restring;
}
2.3发送短信
@Service
@PropertySource(value="classpath:content.properties")
public class PublicSendMesServiceImpl implements PublicSendMesService {
private Logger logger = LoggerFactory.getLogger(PublicSendMesService.class);
@Autowired
private CommonLogMapper commonLogMapper;
@Autowired
private RedisCacheServiceImpl redisCacheServiceImpl;
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Override
public void sendSmsMessage(String smsString) throws ClientException {
//阿里云短信平台的accessKeyId、mq.accessKeySecret
String accessKeyId = Constant.getProperties().getStringProperty("mq.accessKeyId");
System.out.println(accessKeyId);
String accessKeySecret = Constant.getProperties().getStringProperty("mq.accessKeySecret");
// 阿里的默认配置
String product =Constant.getProperties().getStringProperty("sms.product");
String domain = Constant.getProperties().getStringProperty("sms.domain");
String hangzhou= Constant.getProperties().getStringProperty("sms.hangzhou");
//可自助调整超时时间
System.setProperty("sun.net.client.defaultConnectTimeout", "20000");
System.setProperty("sun.net.client.defaultReadTimeout", "20000");
//初始化acsClient,暂不支持region化
IClientProfile profile = DefaultProfile.getProfile(hangzhou, accessKeyId, accessKeySecret);
DefaultProfile.addEndpoint(hangzhou,hangzhou,product,domain);
IAcsClient acsClient = new DefaultAcsClient(profile);
//组装请求对象-具体描述见控制台-文档部分内容
SendSmsRequest request = new SendSmsRequest();
SendSmsResponse sendSmsResponse = new SendSmsResponse();
//cabala或接口传送的数据
JSONObject prams = JSONObject.parseObject(smsString);
logger.info("短信接口接收数据: " + prams.toJSONString());
//此处从redis中取得基础信息
Map<String, Object> etibInfoMap = (Map<String, Object>) redisCacheServiceImpl.getCache("CLAIMS");
System.out.println("缓存中获取数据: " + etibInfoMap.toString());
//从取出的基础信息中取得对应短信类型的数据
Map<String, String> smsMode = (Map<String, String>) etibInfoMap.get(prams.getString("MSGTYPE"));
System.out.println("111" +smsMode);
logger.info("缓存中获取数据: " + smsMode.toString());
logger.info("缓存中获: " + smsMode);
String fieldString = smsMode.get("codeCode");//获取短信模板中的KEY,以英文逗号分隔的字符串
logger.info("缓存中获: " + smsMode.get("codeCode"));
String templateCode = smsMode.get("remark");//获取短信模板代码
logger.info("缓存中获: " + smsMode.get("remark"));
//String signName = "金诚国际";
String signName = smsMode.get("codeName");//获取短信签名
logger.info("缓存中获: " + smsMode.get("codeName"));
String[] fieldStrings = fieldString.split("\\,");
//赋值短信发送所需参数
request.setPhoneNumbers(prams.getString("APPLYTEL"));//手机号
request.setSignName(signName);//短信签名
request.setTemplateCode(templateCode);//短信模板代码
//拼接模板参数
StringBuffer templatePram = new StringBuffer();
templatePram.append("{");
for (int i = 0; i < fieldStrings.length; i ++) {
templatePram.append('\"');
templatePram.append(fieldStrings[i]);
templatePram.append('\"');
templatePram.append(":");
templatePram.append('\"');
templatePram.append(prams.getString(fieldStrings[i]));
templatePram.append('\"');
if (fieldStrings.length - 1 > i) {
templatePram.append(",");
}
}
templatePram.append("}");
logger.info("短信模板参数:" + templatePram.toString());
request.setTemplateParam(templatePram.toString());//短信模板参数
//hint 此处可能会抛出异常,注意catch
System.out.println(request.getTemplateParam());
try {
logger.info("调用短信服务开始");
sendSmsResponse = acsClient.getAcsResponse(request);
if (!"OK".equals(sendSmsResponse.getCode())) {
System.out.println(sendSmsResponse.getMessage());
}
logger.info("调用短信服务结束");
String flag = this.recordSendMsgLog(prams);
logger.info("发送短信时记录日志" + flag);
} catch(ClientException e) {
e.printStackTrace();
}
}
private String recordSendMsgLog(JSONObject prams) {
CommonLog commonLog = new CommonLog();
commonLog.setRequestType(prams.getString("MSGTYPE"));
commonLog.setPolicyNo(prams.containsKey("POICYCODE") ? prams.getString("POICYCODE") : null);
commonLog.setRequestText(prams.toJSONString());
commonLog.setCreatedDate(new Date());
int flag = commonLogMapper.insertCommonLog(commonLog);
if (0 < flag) {
return "success";
}
return "false";
}
}
希望能够帮助到你们