添加邮箱服务器类型标记

This commit is contained in:
duwenyuan 2025-04-30 17:40:03 +08:00
parent 1c4b4af39c
commit 2d96fbe7d0
2 changed files with 158 additions and 135 deletions

View File

@ -21,6 +21,7 @@ import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil; import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.base.entity.postgre.SysEmail; import org.jeecg.modules.base.entity.postgre.SysEmail;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import javax.mail.*; import javax.mail.*;
import javax.mail.internet.InternetAddress; import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMessage;
@ -56,13 +57,21 @@ public class EmailServiceManager {
* 系统启动时间 * 系统启动时间
*/ */
private Date systemStartupTime; private Date systemStartupTime;
/** 邮件接收数量 */ /**
* 邮件接收数量
*/
private Integer receiveNum; private Integer receiveNum;
/** smtp协议的存储对象 */ /**
* smtp协议的存储对象
*/
private IMAPStore store = null; private IMAPStore store = null;
/** 邮件附件临时存储路径 */ /**
* 邮件附件临时存储路径
*/
private String temporaryStoragePath; private String temporaryStoragePath;
/** 收件箱 */ /**
* 收件箱
*/
private Folder folder = null; private Folder folder = null;
private RedisUtil redisUtil; private RedisUtil redisUtil;
@ -72,25 +81,27 @@ public class EmailServiceManager {
private final ReentrantLock lock = new ReentrantLock(); private final ReentrantLock lock = new ReentrantLock();
@NotNull @NotNull
public static EmailServiceManager getInstance(){ public static EmailServiceManager getInstance() {
return new EmailServiceManager(); return new EmailServiceManager();
} }
/** /**
* 初始化邮件服务管理器 * 初始化邮件服务管理器
*
* @param email 邮件属性 * @param email 邮件属性
*/ */
public void init(SysEmail email){ public void init(SysEmail email) {
this.email = email; this.email = email;
} }
/** /**
* 初始化邮件服务管理器 * 初始化邮件服务管理器
*
* @param email 邮件属性 * @param email 邮件属性
*/ */
public void init(SysEmail email, Integer receiveNum, String temporaryStoragePath, public void init(SysEmail email, Integer receiveNum, String temporaryStoragePath,
Date systemStartupTime, SpectrumPathProperties pathProperties,TaskProperties taskProperties, Date systemStartupTime, SpectrumPathProperties pathProperties, TaskProperties taskProperties,
RedisUtil redisUtil){ RedisUtil redisUtil) {
this.email = email; this.email = email;
this.receiveNum = receiveNum; this.receiveNum = receiveNum;
this.temporaryStoragePath = temporaryStoragePath; this.temporaryStoragePath = temporaryStoragePath;
@ -103,18 +114,18 @@ public class EmailServiceManager {
/** /**
* 测试邮件服务连通性 * 测试邮件服务连通性
*/ */
public boolean testConnectEmailServer(){ public boolean testConnectEmailServer() {
Socket socket = new Socket(); Socket socket = new Socket();
boolean flag = false; boolean flag = false;
try { try {
socket.connect(new InetSocketAddress(email.getEmailServerAddress(),email.getPort()),3000); socket.connect(new InetSocketAddress(email.getEmailServerAddress(), email.getPort()), 3000);
log.info("{}邮件服务连接测试成功",email.getName()); log.info("{}邮件服务连接测试成功", email.getName());
flag = true; flag = true;
} catch (IOException e) { } catch (IOException e) {
log.error("{}邮件服务连接测试失败,请检查邮件服务属性配置是否正确或邮件服务未开启,原因: ",email.getName(),e); log.error("{}邮件服务连接测试失败,请检查邮件服务属性配置是否正确或邮件服务未开启,原因: ", email.getName(), e);
}finally { } finally {
try { try {
if(null != socket){ if (null != socket) {
socket.close(); socket.close();
} }
} catch (IOException e) { } catch (IOException e) {
@ -129,12 +140,12 @@ public class EmailServiceManager {
*/ */
public Message[] receiveMail() throws Exception { public Message[] receiveMail() throws Exception {
String status = EmailLogManager.STATUS_SUCCESS; String status = EmailLogManager.STATUS_SUCCESS;
try{ try {
//配置邮件服务属性 //配置邮件服务属性
Properties properties = new Properties(); Properties properties = new Properties();
properties.put("mail.store.protocol", "imap"); properties.put("mail.store.protocol", "imap");
properties.put("mail.imap.host", email.getEmailServerAddress()); properties.put("mail.imap.host", email.getEmailServerAddress());
properties.put("mail.imap.port",email.getPort()); properties.put("mail.imap.port", email.getPort());
properties.put("mail.imap.connectiontimeout", "3000"); properties.put("mail.imap.connectiontimeout", "3000");
properties.put("mail.imap.timeout", "3000"); properties.put("mail.imap.timeout", "3000");
if (email.getIsQiye() == 1) { if (email.getIsQiye() == 1) {
@ -145,10 +156,10 @@ public class EmailServiceManager {
HashMap IAM = new HashMap(); HashMap IAM = new HashMap();
//带上IMAP ID信息由key和value组成例如nameversionvendorsupport-email等 //带上IMAP ID信息由key和value组成例如nameversionvendorsupport-email等
IAM.put("name","myname"); IAM.put("name", "myname");
IAM.put("version","1.0.0"); IAM.put("version", "1.0.0");
IAM.put("vendor","myclient"); IAM.put("vendor", "myclient");
IAM.put("support-email","testmail@test.com"); IAM.put("support-email", "testmail@test.com");
//获取邮件回话 //获取邮件回话
final Session session = Session.getDefaultInstance(properties); final Session session = Session.getDefaultInstance(properties);
@ -157,22 +168,26 @@ public class EmailServiceManager {
//获取smtp协议的存储对象 //获取smtp协议的存储对象
store = (IMAPStore) session.getStore(); store = (IMAPStore) session.getStore();
//连接 //连接
store.connect(email.getUsername(),email.getPassword()); store.connect(email.getUsername(), email.getPassword());
if (email.getEmailServerType()==1) {
// 解决163普通邮箱无法建立连接问题 // 解决163普通邮箱无法建立连接问题
store.id(IAM); store.id(IAM);
}
//获取收件箱 //获取收件箱
folder = store.getFolder("INBOX");//INBOX folder = store.getFolder("INBOX");//INBOX
folder.open(Folder.READ_WRITE); folder.open(Folder.READ_WRITE);
//如果邮箱邮件数量 > 0 //如果邮箱邮件数量 > 0
final int messageCount = folder.getMessageCount(); final int messageCount = folder.getMessageCount();
if(messageCount > 0){ if (messageCount > 0) {
Message[] messages = null; Message[] messages = null;
if(Objects.isNull(this.systemStartupTime)){ if (Objects.isNull(this.systemStartupTime)) {
int finalNum = messageCount > this.receiveNum?this.receiveNum:messageCount; int finalNum = messageCount > this.receiveNum ? this.receiveNum : messageCount;
//邮箱邮件下标是从1开始的 //邮箱邮件下标是从1开始的
return folder.getMessages(1,finalNum); return folder.getMessages(1, finalNum);
} }
SearchTerm searchTerm = new ReceivedDateTerm(ComparisonTerm.GE,this.systemStartupTime); SearchTerm searchTerm = new ReceivedDateTerm(ComparisonTerm.GE, this.systemStartupTime);
messages = folder.search(searchTerm); messages = folder.search(searchTerm);
Arrays.sort(messages, (o1, o2) -> { Arrays.sort(messages, (o1, o2) -> {
try { try {
@ -183,21 +198,21 @@ public class EmailServiceManager {
} }
return 0; return 0;
}); });
if(this.receiveNum >= messages.length){ if (this.receiveNum >= messages.length) {
return messages; return messages;
}else{ } else {
return Arrays.copyOfRange(messages,0,this.receiveNum-1); return Arrays.copyOfRange(messages, 0, this.receiveNum - 1);
} }
} }
} catch (Exception e){ } catch (Exception e) {
status = EmailLogManager.STATUS_ERROR; status = EmailLogManager.STATUS_ERROR;
log.error("Email connection is abnormal, account is {}, service is {},the reason is {}.",email.getName(),email.getEmailServerAddress(),e.getMessage()); log.error("Email connection is abnormal, account is {}, service is {},the reason is {}.", email.getName(), email.getEmailServerAddress(), e.getMessage());
throw e; throw e;
} finally { } finally {
EmailLogEvent connectEvent = new EmailLogEvent(EmailLogManager.GS_TYPE_GET,email,status,EmailLogManager.CONNECT); EmailLogEvent connectEvent = new EmailLogEvent(EmailLogManager.GS_TYPE_GET, email, status, EmailLogManager.CONNECT);
EmailLogManager.getInstance().setConnectLogEvent(connectEvent); EmailLogManager.getInstance().setConnectLogEvent(connectEvent);
//GetAllId C++原业务是把远程邮箱邮件同步到C++本次java编写没有这一步所以和Connect绑定若Connect成功则GetAllId成功 //GetAllId C++原业务是把远程邮箱邮件同步到C++本次java编写没有这一步所以和Connect绑定若Connect成功则GetAllId成功
EmailLogEvent getAllEvent = new EmailLogEvent(EmailLogManager.GS_TYPE_GET,status,EmailLogManager.GETALLID); EmailLogEvent getAllEvent = new EmailLogEvent(EmailLogManager.GS_TYPE_GET, status, EmailLogManager.GETALLID);
EmailLogManager.getInstance().setGetAllIdLogEvent(getAllEvent); EmailLogManager.getInstance().setGetAllIdLogEvent(getAllEvent);
} }
return null; return null;
@ -206,14 +221,14 @@ public class EmailServiceManager {
/* /*
* 测试收件邮箱账号是否可以正常使用 * 测试收件邮箱账号是否可以正常使用
* */ * */
public boolean canReceive(){ public boolean canReceive() {
Integer port = email.getPort(); Integer port = email.getPort();
String username = email.getUsername(); String username = email.getUsername();
String password = email.getPassword(); String password = email.getPassword();
String host = email.getEmailServerAddress(); String host = email.getEmailServerAddress();
Properties props = new Properties(); Properties props = new Properties();
props.put("mail.store.protocol","imap"); props.put("mail.store.protocol", "imap");
props.put("mail.imap.host", host); props.put("mail.imap.host", host);
props.put("mail.imap.port", port); props.put("mail.imap.port", port);
@ -224,11 +239,11 @@ public class EmailServiceManager {
} }
}); });
try(Store store = session.getStore()) { try (Store store = session.getStore()) {
store.connect(host, username, password); store.connect(host, username, password);
return store.isConnected(); return store.isConnected();
} catch (Exception e) { } catch (Exception e) {
log.error("收件邮箱服务[Host: {}, Port: {}, Username: {}]连接异常: {}",host, port, username, e.getMessage()); log.error("收件邮箱服务[Host: {}, Port: {}, Username: {}]连接异常: {}", host, port, username, e.getMessage());
return false; return false;
} }
} }
@ -236,14 +251,14 @@ public class EmailServiceManager {
/* /*
* 测试收件邮箱账号是否可以正常使用(开启了SSL安全验证的邮箱) * 测试收件邮箱账号是否可以正常使用(开启了SSL安全验证的邮箱)
* */ * */
public boolean canReceiveSSL(){ public boolean canReceiveSSL() {
Integer port = email.getPort(); Integer port = email.getPort();
String username = email.getUsername(); String username = email.getUsername();
String password = email.getPassword(); String password = email.getPassword();
String host = email.getEmailServerAddress(); String host = email.getEmailServerAddress();
Properties props = new Properties(); Properties props = new Properties();
props.put("mail.store.protocol","imap"); props.put("mail.store.protocol", "imap");
props.put("mail.imap.host", host); props.put("mail.imap.host", host);
props.put("mail.imap.port", port); props.put("mail.imap.port", port);
props.put("mail.imap.auth", "true"); props.put("mail.imap.auth", "true");
@ -257,11 +272,11 @@ public class EmailServiceManager {
} }
}); });
try(Store store = session.getStore()) { try (Store store = session.getStore()) {
store.connect(host, username, password); store.connect(host, username, password);
return store.isConnected(); return store.isConnected();
} catch (Exception e) { } catch (Exception e) {
log.error("收件邮箱服务SSL[Host: {}, Port: {}, Username: {}]连接异常: {}",host, port, username, e.getMessage()); log.error("收件邮箱服务SSL[Host: {}, Port: {}, Username: {}]连接异常: {}", host, port, username, e.getMessage());
return false; return false;
} }
} }
@ -269,7 +284,7 @@ public class EmailServiceManager {
/* /*
* 测试发件邮箱账号是否可以正常使用 * 测试发件邮箱账号是否可以正常使用
* */ * */
public boolean canSend(){ public boolean canSend() {
Integer port = email.getPort(); Integer port = email.getPort();
String username = email.getUsername(); String username = email.getUsername();
String password = email.getPassword(); String password = email.getPassword();
@ -288,11 +303,11 @@ public class EmailServiceManager {
} }
}); });
try (Transport transport = session.getTransport()){ try (Transport transport = session.getTransport()) {
transport.connect(host, username, password); transport.connect(host, username, password);
return true; return true;
} catch (Exception e) { } catch (Exception e) {
log.error("发件邮箱服务[Host: {}, Port: {}, Username: {}]连接异常: {}",host, port, username, e.getMessage()); log.error("发件邮箱服务[Host: {}, Port: {}, Username: {}]连接异常: {}", host, port, username, e.getMessage());
return false; return false;
} }
} }
@ -300,7 +315,7 @@ public class EmailServiceManager {
/* /*
* 测试发件邮箱账号是否可以正常使用(开启了SSL安全验证的邮箱) * 测试发件邮箱账号是否可以正常使用(开启了SSL安全验证的邮箱)
* */ * */
public boolean canSendSSL(){ public boolean canSendSSL() {
Integer port = email.getPort(); Integer port = email.getPort();
String username = email.getUsername(); String username = email.getUsername();
String password = email.getPassword(); String password = email.getPassword();
@ -321,11 +336,11 @@ public class EmailServiceManager {
} }
}); });
try (Transport transport = session.getTransport()){ try (Transport transport = session.getTransport()) {
transport.connect(host, username, password); transport.connect(host, username, password);
return true; return true;
} catch (Exception e) { } catch (Exception e) {
log.error("发件邮箱服务SSL[Host: {}, Port: {}, Username: {}]连接异常: {}",host, port, username, e.getMessage()); log.error("发件邮箱服务SSL[Host: {}, Port: {}, Username: {}]连接异常: {}", host, port, username, e.getMessage());
return false; return false;
} }
} }
@ -361,7 +376,7 @@ public class EmailServiceManager {
// 发送邮件 // 发送邮件
Transport transport = session.getTransport(); Transport transport = session.getTransport();
transport.connect(email.getUsername(),email.getPassword()); transport.connect(email.getUsername(), email.getPassword());
transport.sendMessage(message, message.getAllRecipients()); transport.sendMessage(message, message.getAllRecipients());
// 关闭资源 // 关闭资源
@ -371,7 +386,7 @@ public class EmailServiceManager {
/** /**
* 发送邮件 群发 * 发送邮件 群发
*/ */
public void sendMail(MessageDTO messageDTO){ public void sendMail(MessageDTO messageDTO) {
// 邮箱连接属性 // 邮箱连接属性
Properties props = new Properties(); Properties props = new Properties();
props.put("mail.transport.protocol", "smtp"); props.put("mail.transport.protocol", "smtp");
@ -396,24 +411,24 @@ public class EmailServiceManager {
InternetAddress.parse(messageDTO.getToUser())); InternetAddress.parse(messageDTO.getToUser()));
// 发送邮件 // 发送邮件
transport = session.getTransport(); transport = session.getTransport();
transport.connect(email.getUsername(),email.getPassword()); transport.connect(email.getUsername(), email.getPassword());
transport.sendMessage(message,message.getAllRecipients()); transport.sendMessage(message, message.getAllRecipients());
} catch (MessagingException e) { } catch (MessagingException e) {
// 无效的电子邮箱导致群发失败,剔除无效邮箱然后重新发送 // 无效的电子邮箱导致群发失败,剔除无效邮箱然后重新发送
Address[] invalid; Address[] invalid;
if (e instanceof SMTPAddressFailedException) { if (e instanceof SMTPAddressFailedException) {
invalid = ((SMTPAddressFailedException) e).getInvalidAddresses(); invalid = ((SMTPAddressFailedException) e).getInvalidAddresses();
reSendMail(invalid,messageDTO); reSendMail(invalid, messageDTO);
} else if (e instanceof SendFailedException) { } else if (e instanceof SendFailedException) {
invalid = ((SendFailedException) e).getInvalidAddresses(); invalid = ((SendFailedException) e).getInvalidAddresses();
reSendMail(invalid,messageDTO); reSendMail(invalid, messageDTO);
} }
}finally { } finally {
if (transport != null){ if (transport != null) {
try { try {
transport.close(); transport.close();
} catch (MessagingException e) { } catch (MessagingException e) {
log.error("Transport关闭失败,{}",e); log.error("Transport关闭失败,{}", e);
} }
} }
} }
@ -425,20 +440,20 @@ public class EmailServiceManager {
* @param invalid 无效电子邮箱列表 * @param invalid 无效电子邮箱列表
* @param messageDTO 消息dto * @param messageDTO 消息dto
*/ */
private void reSendMail(Address[] invalid,MessageDTO messageDTO){ private void reSendMail(Address[] invalid, MessageDTO messageDTO) {
List<String> invalidEmails = Arrays.stream(invalid) List<String> invalidEmails = Arrays.stream(invalid)
.map(address -> address.toString()) .map(address -> address.toString())
.collect(Collectors.toList()); .collect(Collectors.toList());
log.warn("部分或者全部邮件发送失败,无效的电子邮箱:{}",invalidEmails); log.warn("部分或者全部邮件发送失败,无效的电子邮箱:{}", invalidEmails);
String[] allEmails = messageDTO.getToUser().split(SymbolConstant.COMMA); String[] allEmails = messageDTO.getToUser().split(SymbolConstant.COMMA);
String[] emails = new String[]{}; String[] emails = new String[]{};
for (String address : invalidEmails) { for (String address : invalidEmails) {
emails = ArrayUtil.removeEle(allEmails,address); emails = ArrayUtil.removeEle(allEmails, address);
} }
// 如果移除无效电子邮箱后,待发送邮箱不为空 // 如果移除无效电子邮箱后,待发送邮箱不为空
String toUser = Arrays.stream(emails) String toUser = Arrays.stream(emails)
.collect(Collectors.joining(SymbolConstant.COMMA)); .collect(Collectors.joining(SymbolConstant.COMMA));
if (StrUtil.isNotBlank(toUser)){ if (StrUtil.isNotBlank(toUser)) {
messageDTO.setToUser(toUser); messageDTO.setToUser(toUser);
sendMail(messageDTO); sendMail(messageDTO);
} }
@ -446,10 +461,11 @@ public class EmailServiceManager {
/** /**
* 获取邮件主题 * 获取邮件主题
*
* @param message * @param message
* @return * @return
*/ */
public String getMailSubject(@NotNull Message message,Integer batchesCounter) throws MessagingException { public String getMailSubject(@NotNull Message message, Integer batchesCounter) throws MessagingException {
String subject = ""; String subject = "";
String status = EmailLogManager.STATUS_SUCCESS; String status = EmailLogManager.STATUS_SUCCESS;
try { try {
@ -459,34 +475,36 @@ public class EmailServiceManager {
} catch (MessagingException e) { } catch (MessagingException e) {
status = EmailLogManager.STATUS_ERROR; status = EmailLogManager.STATUS_ERROR;
throw e; throw e;
}finally { } finally {
EmailLogEvent event = new EmailLogEvent(batchesCounter,Thread.currentThread().getId(),EmailLogManager.GS_TYPE_GET,status,EmailLogManager.GETIDHEADER); EmailLogEvent event = new EmailLogEvent(batchesCounter, Thread.currentThread().getId(), EmailLogManager.GS_TYPE_GET, status, EmailLogManager.GETIDHEADER);
EmailLogManager.getInstance().offer(Thread.currentThread().getId(),event); EmailLogManager.getInstance().offer(Thread.currentThread().getId(), event);
} }
return subject; return subject;
} }
/** /**
* 获取邮件内容 * 获取邮件内容
*
* @param part * @param part
* @return * @return
* @throws MessagingException * @throws MessagingException
* @throws IOException * @throws IOException
*/ */
public void getMailContent(@NotNull Part part, StringBuilder content) throws MessagingException, IOException { public void getMailContent(@NotNull Part part, StringBuilder content) throws MessagingException, IOException {
if(part.isMimeType(MailContentType.PLAIN.getContentType())){ if (part.isMimeType(MailContentType.PLAIN.getContentType())) {
content.append(part.getContent()); content.append(part.getContent());
}else if(part.isMimeType("multipart/*")){ } else if (part.isMimeType("multipart/*")) {
Multipart multipart = (Multipart) part.getContent(); Multipart multipart = (Multipart) part.getContent();
for(int i=0;i<multipart.getCount();i++) { for (int i = 0; i < multipart.getCount(); i++) {
final Part bodyPart = multipart.getBodyPart(i); final Part bodyPart = multipart.getBodyPart(i);
getMailContent(bodyPart,content); getMailContent(bodyPart, content);
} }
} }
} }
/** /**
* 保存邮件附件 * 保存邮件附件
*
* @param part * @param part
* @throws MessagingException * @throws MessagingException
* @throws IOException * @throws IOException
@ -494,27 +512,27 @@ public class EmailServiceManager {
public List<String> saveAttachment(@NotNull Part part) throws MessagingException, IOException { public List<String> saveAttachment(@NotNull Part part) throws MessagingException, IOException {
List<String> filePathList = Lists.newArrayList(); List<String> filePathList = Lists.newArrayList();
Multipart multipart = (Multipart) part.getContent(); Multipart multipart = (Multipart) part.getContent();
for(int i=0;i<multipart.getCount();i++){ for (int i = 0; i < multipart.getCount(); i++) {
final BodyPart bodyPart = multipart.getBodyPart(i); final BodyPart bodyPart = multipart.getBodyPart(i);
if(Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())){ if (Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
BufferedInputStream bis = null; BufferedInputStream bis = null;
BufferedOutputStream bos = null; BufferedOutputStream bos = null;
try{ try {
final String fileName = MimeUtility.decodeText(bodyPart.getFileName()); final String fileName = MimeUtility.decodeText(bodyPart.getFileName());
bis = new BufferedInputStream(bodyPart.getInputStream()); bis = new BufferedInputStream(bodyPart.getInputStream());
File file = new File(this.temporaryStoragePath+File.separator+fileName); File file = new File(this.temporaryStoragePath + File.separator + fileName);
bos = new BufferedOutputStream(new FileOutputStream(file)); bos = new BufferedOutputStream(new FileOutputStream(file));
byte[] buf = new byte[4096]; byte[] buf = new byte[4096];
int len; int len;
while(-1 != (len = bis.read(buf,0,buf.length))){ while (-1 != (len = bis.read(buf, 0, buf.length))) {
bos.write(buf,0,buf.length); bos.write(buf, 0, buf.length);
} }
filePathList.add(file.getAbsolutePath()); filePathList.add(file.getAbsolutePath());
}finally { } finally {
if(null != bis){ if (null != bis) {
bis.close(); bis.close();
} }
if(null != bos){ if (null != bos) {
bos.flush(); bos.flush();
bos.close(); bos.close();
} }
@ -531,7 +549,7 @@ public class EmailServiceManager {
* 新格式为发件人_主题_年月日_时分秒毫秒_receive_年月日_时分秒毫秒_计数0-10000 * 新格式为发件人_主题_年月日_时分秒毫秒_receive_年月日_时分秒毫秒_计数0-10000
* 当计数大于10000后从0开始服务重启后也从0开始 * 当计数大于10000后从0开始服务重启后也从0开始
*/ */
public File downloadEmailToEmlDir(@NotNull Message message,Integer emailCounter,Integer batchesCounter) throws MessagingException { public File downloadEmailToEmlDir(@NotNull Message message, Integer emailCounter, Integer batchesCounter) throws MessagingException {
synchronized (downloadEmlLocal) { synchronized (downloadEmlLocal) {
String subject = ""; String subject = "";
File emlFile = null; File emlFile = null;
@ -542,14 +560,14 @@ public class EmailServiceManager {
try { try {
//获取发件人 //获取发件人
final String address = ((InternetAddress) message.getFrom()[0]).getAddress(); final String address = ((InternetAddress) message.getFrom()[0]).getAddress();
final String from = address.substring(0,address.indexOf(StringConstant.AT)); final String from = address.substring(0, address.indexOf(StringConstant.AT));
//获取主题 //获取主题
subject = MimeUtility.decodeText(message.getSubject()); subject = MimeUtility.decodeText(message.getSubject());
if(subject.indexOf(StringConstant.SLASH) != -1){ if (subject.indexOf(StringConstant.SLASH) != -1) {
subject = StringUtils.replace(subject,StringConstant.SLASH,""); subject = StringUtils.replace(subject, StringConstant.SLASH, "");
} }
if(subject.indexOf(StringConstant.COLON) != -1){ if (subject.indexOf(StringConstant.COLON) != -1) {
subject = StringUtils.replace(subject,StringConstant.COLON,""); subject = StringUtils.replace(subject, StringConstant.COLON, "");
} }
receivedDate = message.getReceivedDate(); receivedDate = message.getReceivedDate();
StringBuilder fileName = new StringBuilder(); StringBuilder fileName = new StringBuilder();
@ -557,21 +575,21 @@ public class EmailServiceManager {
fileName.append(StringConstant.UNDER_LINE); fileName.append(StringConstant.UNDER_LINE);
fileName.append(subject); fileName.append(subject);
fileName.append(StringConstant.UNDER_LINE); fileName.append(StringConstant.UNDER_LINE);
fileName.append(DateUtils.formatDate(new Date(),"YYMMdd")); fileName.append(DateUtils.formatDate(new Date(), "YYMMdd"));
fileName.append(StringConstant.UNDER_LINE); fileName.append(StringConstant.UNDER_LINE);
fileName.append(DateUtils.formatDate(new Date(),"HHmmssSSS")); fileName.append(DateUtils.formatDate(new Date(), "HHmmssSSS"));
fileName.append(StringConstant.UNDER_LINE); fileName.append(StringConstant.UNDER_LINE);
fileName.append("receive"); fileName.append("receive");
fileName.append(StringConstant.UNDER_LINE); fileName.append(StringConstant.UNDER_LINE);
fileName.append(DateUtils.formatDate(receivedDate,"YYMMdd")); fileName.append(DateUtils.formatDate(receivedDate, "YYMMdd"));
fileName.append(StringConstant.UNDER_LINE); fileName.append(StringConstant.UNDER_LINE);
fileName.append(DateUtils.formatDate(receivedDate,"HHmmssSSS")); fileName.append(DateUtils.formatDate(receivedDate, "HHmmssSSS"));
fileName.append(StringConstant.UNDER_LINE); fileName.append(StringConstant.UNDER_LINE);
fileName.append(emailCounter); fileName.append(emailCounter);
fileName.append(SAVE_EML_SUFFIX); fileName.append(SAVE_EML_SUFFIX);
final String rootPath = spectrumPathProperties.getRootPath(); final String rootPath = spectrumPathProperties.getRootPath();
final String emlPath = spectrumPathProperties.getEmlPath(); final String emlPath = spectrumPathProperties.getEmlPath();
emlFile = new File(rootPath+emlPath+File.separator+fileName); emlFile = new File(rootPath + emlPath + File.separator + fileName);
// outputStream = new FileOutputStream(emlFile); // outputStream = new FileOutputStream(emlFile);
// message.writeTo(outputStream); // message.writeTo(outputStream);
@ -591,13 +609,13 @@ public class EmailServiceManager {
String errorMsg = StrUtil.format("The email download failed, the subject of the email is {}, the reason is {}.", subject, e.getMessage()); String errorMsg = StrUtil.format("The email download failed, the subject of the email is {}, the reason is {}.", subject, e.getMessage());
log.error(errorMsg); log.error(errorMsg);
throw new DownloadEmailException(errorMsg); throw new DownloadEmailException(errorMsg);
}catch (Exception e) { } catch (Exception e) {
log.error("",e); log.error("", e);
throw new RuntimeException(e); throw new RuntimeException(e);
}finally { } finally {
EmailLogEvent event = new EmailLogEvent(batchesCounter,Thread.currentThread().getId(),EmailLogManager.GS_TYPE_GET,status,EmailLogManager.GETIDEML,subject,DateUtils.formatDate(receivedDate,"yyyy-MM-dd HH:mm:ss:SSS"), EmailLogEvent event = new EmailLogEvent(batchesCounter, Thread.currentThread().getId(), EmailLogManager.GS_TYPE_GET, status, EmailLogManager.GETIDEML, subject, DateUtils.formatDate(receivedDate, "yyyy-MM-dd HH:mm:ss:SSS"),
(Objects.isNull(emlFile)?" ":emlFile.getAbsolutePath())); (Objects.isNull(emlFile) ? " " : emlFile.getAbsolutePath()));
EmailLogManager.getInstance().offer(Thread.currentThread().getId(),event); EmailLogManager.getInstance().offer(Thread.currentThread().getId(), event);
try { try {
if (Objects.nonNull(inputStream)) { if (Objects.nonNull(inputStream)) {
inputStream.close(); inputStream.close();
@ -648,7 +666,7 @@ public class EmailServiceManager {
throw new RuntimeException("下载 eml 执行超时"); throw new RuntimeException("下载 eml 执行超时");
} }
}*/ }*/
public File executeWithLock(Message message,Integer emailCounter,Integer batchesCounter) throws MessagingException { public File executeWithLock(Message message, Integer emailCounter, Integer batchesCounter) throws MessagingException {
String subject = ""; String subject = "";
File emlFile = null; File emlFile = null;
@ -658,14 +676,14 @@ public class EmailServiceManager {
// 获取锁 设置超时 // 获取锁 设置超时
//获取发件人 //获取发件人
final String address = ((InternetAddress) message.getFrom()[0]).getAddress(); final String address = ((InternetAddress) message.getFrom()[0]).getAddress();
final String from = address.substring(0,address.indexOf(StringConstant.AT)); final String from = address.substring(0, address.indexOf(StringConstant.AT));
//获取主题 //获取主题
subject = MimeUtility.decodeText(message.getSubject()); subject = MimeUtility.decodeText(message.getSubject());
if(subject.contains(StringConstant.SLASH)){ if (subject.contains(StringConstant.SLASH)) {
subject = StringUtils.replace(subject,StringConstant.SLASH,""); subject = StringUtils.replace(subject, StringConstant.SLASH, "");
} }
if(subject.contains(StringConstant.COLON)){ if (subject.contains(StringConstant.COLON)) {
subject = StringUtils.replace(subject,StringConstant.COLON,""); subject = StringUtils.replace(subject, StringConstant.COLON, "");
} }
receivedDate = message.getReceivedDate(); receivedDate = message.getReceivedDate();
StringBuilder fileName = new StringBuilder(); StringBuilder fileName = new StringBuilder();
@ -673,21 +691,21 @@ public class EmailServiceManager {
fileName.append(StringConstant.UNDER_LINE); fileName.append(StringConstant.UNDER_LINE);
fileName.append(subject); fileName.append(subject);
fileName.append(StringConstant.UNDER_LINE); fileName.append(StringConstant.UNDER_LINE);
fileName.append(DateUtils.formatDate(new Date(),"YYMMdd")); fileName.append(DateUtils.formatDate(new Date(), "YYMMdd"));
fileName.append(StringConstant.UNDER_LINE); fileName.append(StringConstant.UNDER_LINE);
fileName.append(DateUtils.formatDate(new Date(),"HHmmssSSS")); fileName.append(DateUtils.formatDate(new Date(), "HHmmssSSS"));
fileName.append(StringConstant.UNDER_LINE); fileName.append(StringConstant.UNDER_LINE);
fileName.append("receive"); fileName.append("receive");
fileName.append(StringConstant.UNDER_LINE); fileName.append(StringConstant.UNDER_LINE);
fileName.append(DateUtils.formatDate(receivedDate,"YYMMdd")); fileName.append(DateUtils.formatDate(receivedDate, "YYMMdd"));
fileName.append(StringConstant.UNDER_LINE); fileName.append(StringConstant.UNDER_LINE);
fileName.append(DateUtils.formatDate(receivedDate,"HHmmssSSS")); fileName.append(DateUtils.formatDate(receivedDate, "HHmmssSSS"));
fileName.append(StringConstant.UNDER_LINE); fileName.append(StringConstant.UNDER_LINE);
fileName.append(emailCounter); fileName.append(emailCounter);
fileName.append(SAVE_EML_SUFFIX); fileName.append(SAVE_EML_SUFFIX);
final String rootPath = spectrumPathProperties.getRootPath(); final String rootPath = spectrumPathProperties.getRootPath();
final String emlPath = spectrumPathProperties.getEmlPath(); final String emlPath = spectrumPathProperties.getEmlPath();
emlFile = new File(rootPath+emlPath+File.separator+fileName); emlFile = new File(rootPath + emlPath + File.separator + fileName);
// Thread.sleep(6000l); // Thread.sleep(6000l);
// try(FileOutputStream outputStream = new FileOutputStream(emlFile)) { // try(FileOutputStream outputStream = new FileOutputStream(emlFile)) {
// message.writeTo(outputStream); // message.writeTo(outputStream);
@ -701,11 +719,11 @@ public class EmailServiceManager {
log.error(errorMsg); log.error(errorMsg);
throw new DownloadEmailException(errorMsg); throw new DownloadEmailException(errorMsg);
} catch (Exception e) { } catch (Exception e) {
log.error("",e); log.error("", e);
} finally { } finally {
EmailLogEvent event = new EmailLogEvent(batchesCounter,Thread.currentThread().getId(),EmailLogManager.GS_TYPE_GET,status,EmailLogManager.GETIDEML,subject,DateUtils.formatDate(receivedDate,"yyyy-MM-dd HH:mm:ss:SSS"), EmailLogEvent event = new EmailLogEvent(batchesCounter, Thread.currentThread().getId(), EmailLogManager.GS_TYPE_GET, status, EmailLogManager.GETIDEML, subject, DateUtils.formatDate(receivedDate, "yyyy-MM-dd HH:mm:ss:SSS"),
(Objects.isNull(emlFile)?" ":emlFile.getAbsolutePath())); (Objects.isNull(emlFile) ? " " : emlFile.getAbsolutePath()));
EmailLogManager.getInstance().offer(Thread.currentThread().getId(),event); EmailLogManager.getInstance().offer(Thread.currentThread().getId(), event);
} }
return emlFile; return emlFile;
} }
@ -713,45 +731,47 @@ public class EmailServiceManager {
public void a(AtomicReference<FileOutputStream> outputStream, Message message) throws MessagingException, IOException { public void a(AtomicReference<FileOutputStream> outputStream, Message message) throws MessagingException, IOException {
message.writeTo(outputStream.get()); message.writeTo(outputStream.get());
} }
/** /**
* 删除邮件 * 删除邮件
*
* @param message * @param message
* @throws MessagingException * @throws MessagingException
*/ */
public void removeMail(@NotNull Message message,Integer batchesCounter){ public void removeMail(@NotNull Message message, Integer batchesCounter) {
String status = EmailLogManager.STATUS_SUCCESS; String status = EmailLogManager.STATUS_SUCCESS;
String subject = ""; String subject = "";
Date receivedDate = null; Date receivedDate = null;
try { try {
subject = MimeUtility.decodeText(message.getSubject()); subject = MimeUtility.decodeText(message.getSubject());
receivedDate = message.getReceivedDate(); receivedDate = message.getReceivedDate();
message.setFlag(Flags.Flag.DELETED,true); message.setFlag(Flags.Flag.DELETED, true);
// log.info("EmailServiceManager: Remove Email:{},receiveTime:{}",message.getSubject(), DateUtils.formatDate(message.getReceivedDate(),"yyyy-MM-dd HH:mm:ss")); // log.info("EmailServiceManager: Remove Email:{},receiveTime:{}",message.getSubject(), DateUtils.formatDate(message.getReceivedDate(),"yyyy-MM-dd HH:mm:ss"));
} catch (MessagingException | UnsupportedEncodingException e) { } catch (MessagingException | UnsupportedEncodingException e) {
status = EmailLogManager.STATUS_ERROR; status = EmailLogManager.STATUS_ERROR;
log.error("Email deletion failed, the subject of the email is :{}, the reason is :",subject, e); log.error("Email deletion failed, the subject of the email is :{}, the reason is :", subject, e);
e.printStackTrace(); e.printStackTrace();
} catch (Exception e) { } catch (Exception e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
} finally { } finally {
EmailLogEvent removeEvent = new EmailLogEvent(batchesCounter,Thread.currentThread().getId(),EmailLogManager.GS_TYPE_GET,status,EmailLogManager.DELETEID,subject,DateUtils.formatDate(receivedDate,"yyyy-MM-dd HH:mm:ss:SSS")); EmailLogEvent removeEvent = new EmailLogEvent(batchesCounter, Thread.currentThread().getId(), EmailLogManager.GS_TYPE_GET, status, EmailLogManager.DELETEID, subject, DateUtils.formatDate(receivedDate, "yyyy-MM-dd HH:mm:ss:SSS"));
EmailLogManager.getInstance().offer(Thread.currentThread().getId(),removeEvent); EmailLogManager.getInstance().offer(Thread.currentThread().getId(), removeEvent);
//这里删除和彻底删除一起写入日志java和C++处理有差异java是在连接关闭时彻底删除的 //这里删除和彻底删除一起写入日志java和C++处理有差异java是在连接关闭时彻底删除的
EmailLogEvent expungeEvent = new EmailLogEvent(batchesCounter,Thread.currentThread().getId(),EmailLogManager.GS_TYPE_GET,status,EmailLogManager.EXPUNGE,subject,DateUtils.formatDate(receivedDate,"yyyy-MM-dd HH:mm:ss:SSS")); EmailLogEvent expungeEvent = new EmailLogEvent(batchesCounter, Thread.currentThread().getId(), EmailLogManager.GS_TYPE_GET, status, EmailLogManager.EXPUNGE, subject, DateUtils.formatDate(receivedDate, "yyyy-MM-dd HH:mm:ss:SSS"));
EmailLogManager.getInstance().offer(Thread.currentThread().getId(),expungeEvent); EmailLogManager.getInstance().offer(Thread.currentThread().getId(), expungeEvent);
} }
} }
/** /**
* 关闭邮件服务连接资源 * 关闭邮件服务连接资源
*/ */
public void close(List<String> messageIds){ public void close(List<String> messageIds) {
try { try {
if(null != folder){ if (null != folder) {
folder.expunge(); folder.expunge();
folder.close(); folder.close();
} }
if(null != store){ if (null != store) {
store.close(); store.close();
} }
log.info("{}: EmailServiceManage资源关闭完成.", Thread.currentThread().getName()); log.info("{}: EmailServiceManage资源关闭完成.", Thread.currentThread().getName());
@ -760,7 +780,7 @@ public class EmailServiceManager {
// redisUtil.del(key); // redisUtil.del(key);
// } // }
} catch (MessagingException e) { } catch (MessagingException e) {
log.error("Email closure failed, email address is: {}, reason is: {}",email.getUsername(),e); log.error("Email closure failed, email address is: {}, reason is: {}", email.getUsername(), e);
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -768,18 +788,19 @@ public class EmailServiceManager {
/** /**
* 校验邮件 * 校验邮件
* 若此次获取的邮件是上次删除失败的邮件直接删除 * 若此次获取的邮件是上次删除失败的邮件直接删除
*
* @param message * @param message
*/ */
public boolean check(Message message,String messageId){ public boolean check(Message message, String messageId) {
boolean exist = false; boolean exist = false;
try { try {
String key = RedisConstant.EMAIL_MSG_ID+StringConstant.COLON+messageId; String key = RedisConstant.EMAIL_MSG_ID + StringConstant.COLON + messageId;
int numberKey = redisUtil.get(key) != null? (int) redisUtil.get(key):0; int numberKey = redisUtil.get(key) != null ? (int) redisUtil.get(key) : 0;
// exist = redisUtil.hasKey(key); // exist = redisUtil.hasKey(key);
if(numberKey >= taskProperties.getForceDeletedNumber()){ if (numberKey >= taskProperties.getForceDeletedNumber()) {
exist = true; exist = true;
log.info("Check: Remove Email:{},receiveTime:{}",message.getSubject(), DateUtils.formatDate(message.getReceivedDate(),"yyyy-MM-dd HH:mm:ss")); log.info("Check: Remove Email:{},receiveTime:{}", message.getSubject(), DateUtils.formatDate(message.getReceivedDate(), "yyyy-MM-dd HH:mm:ss"));
message.setFlag(Flags.Flag.DELETED,true); message.setFlag(Flags.Flag.DELETED, true);
redisUtil.del(key); redisUtil.del(key);
} }
return exist; return exist;

View File

@ -94,4 +94,6 @@ public class SysEmail implements Serializable {
*/ */
@TableField(value = "update_by") @TableField(value = "update_by")
private String updateBy; private String updateBy;
@TableField(value = "email_server_type")
private Integer emailServerType;
} }