短信邮件完善

This commit is contained in:
18792927508
2024-05-29 13:41:49 +08:00
parent 44babb09b1
commit 8261c52673
62 changed files with 2530 additions and 1373 deletions
@@ -156,4 +156,9 @@ public class Constants
"org.springframework", "org.apache", "com.ruoyi.common.utils.file", "com.ruoyi.common.config" };
// 中文逗号分隔符
public static final String CN_SPLIT_COMMA = ",";
/**
* 会议主键Id
*/
public static final String MEETING_KEY = "meeting_key";
}
@@ -0,0 +1,64 @@
package com.ruoyi.common.enums;
/**
* @author wangqiong
* @description 短信状态枚举
* @date 2023-11-17 14:05
*/
public enum SMSStatusEnum
{
SUCCESS(1, "成功"),
SENDING(2, "发送中"),
FAIL(3, "失败"),
;
private final Integer code;
private final String text;
SMSStatusEnum(Integer code, String text)
{
this.code = code;
this.text = text;
}
public Integer getCode()
{
return code;
}
public String getText()
{
return text;
}
/**
* 根据code获取text
* @param codeNo
* @return
*/
public static String getTextByCode(Integer codeNo){
for (SMSStatusEnum value : SMSStatusEnum.values()) {
if (value.getCode().equals(codeNo)){
return value.getText();
}
}
return codeNo.toString();
}
/**
* 根据text获取code
* @param textStr
* @return
*/
public static String getCodeByText(String textStr){
for (SMSStatusEnum value : SMSStatusEnum.values()) {
if (value.getText().equals(textStr)){
return value.getText();
}
}
return textStr;
}
}
@@ -2,10 +2,12 @@ package com.ruoyi.common.utils;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.utils.uuid.UUID;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
@@ -49,12 +51,12 @@ public class EmailOutUtil {
// private static String fromOut;
@Value("${spring.mail.host}")
private String hostOut;
// @Value("${spring.mail.username}")
// private String usernameOut;
private String usernameOut="wq18792927508@163.com";
// @Value("${spring.mail.password}")
// private String passwordOut;
private String passwordOut= "WDFHKSEMCKVRELEA";
@Value("${spring.mail.username}")
private String usernameOut;
@Value("${spring.mail.password}")
private String passwordOut;
@Value("${spring.mail.port}")
private Integer portOut;
@@ -76,18 +78,29 @@ public class EmailOutUtil {
* @param subject 邮件主题
* @param content 邮件内容(发送内容)
*/
public void sendMessage(String to, String subject, String content, String from, JavaMailSender mailSender) {
// 创建一个邮件对象
SimpleMailMessage msg = new SimpleMailMessage();
msg.setFrom(from);
msg.setTo(to);
// 设置邮件主题
msg.setSubject(subject);
// 设置邮件内容
msg.setText(content);
// 发送邮件
mailSender.send(msg);
////System.out.println("发送成功:" + from + ":to:" + to);
public Boolean sendMessage(String to, String subject, String content, String from, JavaMailSender mailSender) {
try {
if(mailSender==null){
mailSender= rebuildMailSender();
}
// 创建一个邮件对象
SimpleMailMessage msg = new SimpleMailMessage();
if(StrUtil.isEmpty(from)){
msg.setFrom(usernameOut);
}else {
msg.setFrom(from);
}
msg.setTo(to);
// 设置邮件主题
msg.setSubject(subject);
// 设置邮件内容
msg.setText(content);
// 发送邮件
mailSender.send(msg);
} catch (MailException e) {
return false;
}
return true;
}
/**
@@ -95,14 +108,14 @@ public class EmailOutUtil {
* @param message 邮件内容
* @param subject 邮件主题
* @param fileList 邮件附件
* @param fileNameMap 附件名称map,附件路径-附件名称
*/
public Boolean sendEmil(String to, String message, String subject, List<File> fileList, File file) {
public Boolean sendEmil(String to, String message, String subject, List<File> fileList, File file,Map<String,String> fileNameMap) {
try {
String messageContent = "<html><body><p style=\"font-family: Arial, sans-serif; font-size: 18px;\">"+message+"。</p></body></html>";
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(messageContent, "text/html;charset=utf-8");
messageBodyPart.setContentID(UUID.randomUUID().toString());
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
//设置邮件会话参数
Properties props = new Properties();
@@ -154,7 +167,10 @@ public class EmailOutUtil {
for (File tempfile : fileList) {
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.attachFile(tempfile);
attachmentPart.setFileName(MimeUtility.encodeText(tempfile.getName()));
// 设置附件名称
if(fileNameMap!=null && fileNameMap.containsKey(tempfile.getPath())) {
attachmentPart.setFileName(MimeUtility.encodeText(fileNameMap.get(tempfile.getPath())));
}
multipart.addBodyPart(attachmentPart);
}
msg.setContent(multipart);
@@ -273,40 +289,40 @@ public class EmailOutUtil {
}
return flag;
}
public void buildReceiveConnect() throws Exception {
public void buildReceiveConnect() throws Exception {
//POP3主机名
String host = "pop3.163.com";
//设置传输协议
String protocol = "pop3";
//用户账号
String username = "wq18792927508@163.com";
//密码或者授权码
String password = "WDFHKSEMCKVRELEA";
/*
* 获取Session
*/
Properties props = new Properties();
//协议
props.setProperty("mail.store.protocol", protocol);
//POP3主机名
props.setProperty("mail.pop3.host", host);
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.pop3.default-encoding", "UTF-8");
Session session = Session.getDefaultInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(usernameOut, passwordOut);
}
});
URLName urlName = new URLName(protocol, host, 110, null, username, password);
Store store = session.getStore(urlName);
store.connect(username, password);
//POP3主机名
String host = "pop3.163.com";
//设置传输协议
String protocol = "pop3";
//用户账号
String username = "wq18792927508@163.com";
//密码或者授权码
String password = "WDFHKSEMCKVRELEA";
/*
* 获取Session
*/
Properties props = new Properties();
//协议
props.setProperty("mail.store.protocol", protocol);
//POP3主机名
props.setProperty("mail.pop3.host", host);
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.pop3.default-encoding", "UTF-8");
Session session = Session.getDefaultInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(usernameOut, passwordOut);
}
});
URLName urlName = new URLName(protocol, host, 110, null, username, password);
Store store = session.getStore(urlName);
store.connect(username, password);
Folder folder = store.getFolder("INBOX");
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
folder.open(Folder.READ_ONLY);
}
/**
@@ -350,14 +366,14 @@ public void buildReceiveConnect() throws Exception {
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
SearchTerm orTerm = new SubjectTerm("退信");
// Message[] messages = folder.search(orTerm);
// Message[] messages = folder.search(orTerm);
Date endTime= new Date();
long oneDayMillis=24*60*60*1000L;
Date startTime=new Date(endTime.getTime()-oneDayMillis);
// SearchTerm comparisonTermGe = new SentDateTerm(ComparisonTerm.GE, startTime);
// SearchTerm comparisonTermLe = new SentDateTerm(ComparisonTerm.LE, endTime);
// SearchTerm comparisonAndTerm = new AndTerm(comparisonTermGe, comparisonTermLe);
// SearchTerm searchTerm = new AndTerm(comparisonAndTerm, orTerm);
// SearchTerm comparisonTermGe = new SentDateTerm(ComparisonTerm.GE, startTime);
// SearchTerm comparisonTermLe = new SentDateTerm(ComparisonTerm.LE, endTime);
// SearchTerm comparisonAndTerm = new AndTerm(comparisonTermGe, comparisonTermLe);
// SearchTerm searchTerm = new AndTerm(comparisonAndTerm, orTerm);
Message[] messages = folder.search(orTerm);
if (messages != null) {
@@ -376,7 +392,7 @@ public void buildReceiveConnect() throws Exception {
folder.close(false);
store.close();
} catch (Exception e) {
return messageIds;
return messageIds;
}
return messageIds;
}
@@ -397,32 +413,32 @@ public void buildReceiveConnect() throws Exception {
}
}
public static String getMessageId(Part part) throws Exception {
if (!part.isMimeType("multipart/*")) {
return "";
}
if (!part.isMimeType("multipart/*")) {
return "";
}
Multipart multipart = (Multipart) part.getContent();
for (int i = 0; i < multipart.getCount(); i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
Multipart multipart = (Multipart) part.getContent();
for (int i = 0; i < multipart.getCount(); i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
if (part.isMimeType("message/rfc822")) {
return getMessageId((Part) part.getContent());
}
InputStream inputStream = bodyPart.getInputStream();
try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
String strLine;
while ((strLine = br.readLine()) != null) {
if (strLine.startsWith("Message_Id:")) {
String[] split = strLine.split("Message_Id:");
return split.length > 1 ? split[1].trim() : null;
}
}
}
}
return "";
if (part.isMimeType("message/rfc822")) {
return getMessageId((Part) part.getContent());
}
InputStream inputStream = bodyPart.getInputStream();
try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
String strLine;
while ((strLine = br.readLine()) != null) {
if (strLine.startsWith("Message_Id:")) {
String[] split = strLine.split("Message_Id:");
return split.length > 1 ? split[1].trim() : null;
}
}
}
}
return "";
}
//检查退信邮件
@@ -1,78 +0,0 @@
package com.ruoyi.common.utils;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.cvm.v20170312.CvmClient;
import com.tencentcloudapi.cvm.v20170312.models.DescribeRegionsRequest;
import com.tencentcloudapi.cvm.v20170312.models.DescribeRegionsResponse;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20210111.models.SendStatus;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import java.util.Objects;
@Slf4j
public class SmsUtils {
//应用id
private static final String SDK_APP_ID = "1400854852";
//API的SecretId
private static final String SECRET_ID = "AKIDeEf2A8uX1HSainvvnXAc3X9ZlhtyvkMp";
//API的SecretKey
private static final String SECRET_KEY = "QjphKo8zkHZigT8j9PVtFPJyfIvO3d6V";
//签名内容
private static final String SIGN_NAME = "乙巢智慧仲裁网";
public static Boolean sendSms(SendSmsRequest request) {
Credential cred = new Credential(SECRET_ID, SECRET_KEY );
SmsClient client = new SmsClient(cred, "ap-guangzhou");
final var req = new com.tencentcloudapi.sms.v20210111.models.SendSmsRequest();
req.setPhoneNumberSet(new String[]{"+86" + request.getPhone()});
req.setSmsSdkAppId(SDK_APP_ID );
req.setSignName(SIGN_NAME);
req.setTemplateId(request.getTemplateId());
req.setTemplateParamSet(request.getTemplateParamSet());
SendSmsResponse res = null;
try {
res = client.SendSms(req);
} catch (TencentCloudSDKException e) {
log.error("发送短信出错:", e);
return Boolean.FALSE;
}
SendStatus sendStatus = res.getSendStatusSet()[0];
log.info("发送短信结果:Code={}, Message={}", sendStatus.getCode(), sendStatus.getMessage());
if (Objects.nonNull(res.getSendStatusSet()) && res.getSendStatusSet().length > 0 && "Ok".equals(res.getSendStatusSet()[0].getCode())){
return Boolean.TRUE;
}
return Boolean.FALSE;
}
/**
* 参数对象
*/
@Data
public static class SendSmsRequest {
/**
* 电话
*/
private String phone;
/**
* 模板 ID: 必须填写已审核通过的模板 ID
*/
private String templateId;
/**
* 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致,若无模板参数,则设置为空
*/
private String[] templateParamSet;
private Long caseId;
}
}
@@ -0,0 +1,23 @@
package com.ruoyi.common.utils;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.*;
/**
* @Author: ymbgy
* @Date: 2022-09-23 10:06
*/
public class ThreadUtil {
public static ExecutorService createThreadPool() {
//获取系统处理器个数,作为线程池数量
int nThreads = Runtime.getRuntime().availableProcessors();
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
.setNameFormat("demo-pool-%d").build();
//Thread Pool
ExecutorService executor = new ThreadPoolExecutor(nThreads, 200,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
return executor;
}
}