package com.yc.crm.mail.service;
|
|
import com.sun.mail.imap.IMAPBodyPart;
|
import com.sun.mail.imap.IMAPStore;
|
import com.yc.action.grid.GridUtils;
|
import com.yc.crm.mail.entity.T482102Entity;
|
import com.yc.crm.mail.entity.t482101HEntity;
|
import com.yc.crm.mail.entity.t482101HList;
|
import com.yc.entity.AttachmentConfig;
|
import com.yc.entity.DataSourceEntity;
|
import com.yc.entity.attachment.AttachmentEntity;
|
import com.yc.entity.attachment.AttachmentWhereEntity;
|
import com.yc.factory.FactoryBean;
|
import com.yc.multiData.MultiDataSource;
|
import com.yc.sdk.shopping.service.imagedata.ShoppingImageDataIfc;
|
import com.yc.service.BaseService;
|
import com.yc.service.upload.AttachmentIfc;
|
import com.yc.utils.SessionKey;
|
import org.apache.commons.io.FileUtils;
|
import org.apache.commons.lang3.StringUtils;
|
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.jdbc.core.BeanPropertyRowMapper;
|
import org.springframework.stereotype.Service;
|
|
import javax.mail.*;
|
import javax.mail.internet.*;
|
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpSession;
|
import java.io.ByteArrayInputStream;
|
import java.io.File;
|
import java.io.IOException;
|
import java.io.InputStream;
|
import java.text.SimpleDateFormat;
|
import java.util.*;
|
import java.util.regex.Pattern;
|
import java.util.stream.Collectors;
|
|
/**
|
* @BelongsProject: eCoWorksV3
|
* @BelongsPackage: com.yc.crm.mail.service
|
* @author: xinyb
|
* @CreateTime: 2024-08-06 09:57
|
* @Description:
|
*/
|
@Service
|
public class MailImpl extends BaseService implements MailIfc {
|
|
@Autowired
|
MailAccountIfc emailAccountIfc;
|
@Autowired
|
ShoppingImageDataIfc imgData;
|
|
final static String shoppingImageServer = AttachmentConfig.get("attachment.server");
|
|
@Override
|
public t482101HEntity saveReceivingMail(t482101HEntity m) {
|
String sql = "set nocount on\n";
|
try {
|
if (StringUtils.isBlank(m.getDocCode())) {
|
sql += "declare @docCode varchar(50) \n";
|
sql += "exec sp_newdoccode 482101," + GridUtils.prossSqlParm(m.getUserCode()) + ",@docCode output \n";
|
sql += "insert into t482101H(companyId,companyName,formId,docCode,docdate,PeriodID,postCode,postname,mailType,sender,receiver," +
|
"cc,bcc,subject,userCode,userName,content,plain_text,file_unid,messageId,read_flag,delete_flag,create_time,update_time,receive_time," +
|
"attach_flag) values ";
|
sql += "(" + GridUtils.prossSqlParm(m.getCompanyId()) + "," + GridUtils.prossSqlParm(m.getCompanyName()) + ",482101," +
|
"@docCode,convert(varchar(10),getdate(),120),convert(varchar(7),getdate(),120),"
|
+ GridUtils.prossSqlParm(m.getUserCode()) + "," + GridUtils.prossSqlParm(m.getUserName()) + "," +
|
+m.getMailType() + "," + GridUtils.prossSqlParm(m.getSender()) + "," +
|
GridUtils.prossSqlParm(StringUtils.join(m.getReceiver(), ",")) + "," + GridUtils.prossSqlParm(StringUtils.join(m.getCc(), ",")) + "," +
|
GridUtils.prossSqlParm(StringUtils.join(m.getBcc(), ",")) + "," +
|
GridUtils.prossSqlParm(m.getSubject()) + "," + GridUtils.prossSqlParm(m.getUserCode()) + "," + GridUtils.prossSqlParm(m.getUserName()) + "," +
|
GridUtils.prossSqlParm(m.getContent()) + "," + GridUtils.prossSqlParm(m.getPlainText()) + "," + GridUtils.prossSqlParm(m.getFileUNID()) + "," + GridUtils.prossSqlParm(m.getMessageId()) + "," +
|
m.getReadFlag() + "," + m.getDeleteFlag() + ",getdate(),getdate()," + GridUtils.prossSqlParm(m.getReceiveTime()) + "," + m.getAttachFlag() + ") \n";
|
sql += "select @docCode as docCode";
|
String docCode = jdbcTemplate.queryForObject(sql, String.class);
|
if (StringUtils.isNotBlank(docCode)) {
|
m.setDocCode(docCode);
|
}
|
} else {
|
updateReceivingMail(m);//修改
|
}
|
return m;
|
} catch (Exception e) {
|
throw e;
|
}
|
}
|
|
@Override
|
public void saveReceivingMailList(List<t482101HEntity> mail) {
|
String sql = "set nocount on\n";
|
try {
|
sql += "declare @docCode varchar(50) \n";
|
for (t482101HEntity m : mail) {//遍历内容
|
sql += "exec sp_newdoccode 482101," + GridUtils.prossSqlParm(m.getUserCode()) + ",@docCode output \n";
|
sql += "insert into t482101H(companyId,companyName,formId,docCode,docdate,PeriodID,postCode,postname,mailType,sender,receiver," +
|
"cc,bcc,subject,userCode,userName,content,plain_text,file_unid,messageId,read_flag,delete_flag,create_time,update_time,receive_time," +
|
"attach_flag) values ";
|
sql += "(" + GridUtils.prossSqlParm(m.getCompanyId()) + "," + GridUtils.prossSqlParm(m.getCompanyName()) + ",482101," +
|
"@docCode,convert(varchar(10),getdate(),120),convert(varchar(7),getdate(),120),"
|
+ GridUtils.prossSqlParm(m.getUserCode()) + "," + GridUtils.prossSqlParm(m.getUserName()) + "," +
|
+m.getMailType() + "," + GridUtils.prossSqlParm(m.getSender()) + "," +
|
GridUtils.prossSqlParm(StringUtils.join(m.getReceiver(), ",")) + "," + GridUtils.prossSqlParm(StringUtils.join(m.getCc(), ",")) + "," +
|
GridUtils.prossSqlParm(StringUtils.join(m.getBcc(), ",")) + "," +
|
GridUtils.prossSqlParm(m.getSubject()) + "," + GridUtils.prossSqlParm(m.getUserCode()) + "," + GridUtils.prossSqlParm(m.getUserName()) + "," +
|
GridUtils.prossSqlParm(m.getContent()) + "," + GridUtils.prossSqlParm(m.getPlainText()) + "," + GridUtils.prossSqlParm(m.getFileUNID()) + "," + GridUtils.prossSqlParm(m.getMessageId()) + "," +
|
m.getReadFlag() + "," + m.getDeleteFlag() + ",getdate(),getdate()," + GridUtils.prossSqlParm(m.getReceiveTime()) + "," +
|
m.getAttachFlag() + ") \n";
|
// sql +="exec postt482101V3 '' ,'',''";
|
}
|
jdbcTemplate.update(sql);
|
} catch (Exception e) {
|
throw e;
|
}
|
}
|
|
@Override
|
public Integer updateReceivingMail(t482101HEntity mail) {
|
String sql = "set nocount on\n";
|
try {
|
sql += "update t482101H set sender=" + GridUtils.prossSqlParm(mail.getSender()) + ",receiver=" + GridUtils.prossSqlParm(StringUtils.join(mail.getReceiver(), ",")) + "," +
|
"cc=" + GridUtils.prossSqlParm(StringUtils.join(mail.getCc(), ",")) + ",bcc=" + GridUtils.prossSqlParm(StringUtils.join(mail.getBcc(), ",")) + ",subject=" + GridUtils.prossSqlParm(mail.getSubject()) + "," +
|
"content=" + GridUtils.prossSqlParm(mail.getContent()) + ",file_unid=" + GridUtils.prossSqlParm(mail.getFileUNID()) + ",mailType=" + mail.getMailType() + "," +
|
"update_time=getdate() \n";
|
sql += " where docCode=" + GridUtils.prossSqlParm(mail.getDocCode()) + "\n";
|
sql += "select @@ROWCOUNT";
|
return jdbcTemplate.queryForObject(sql, Integer.class);
|
} catch (Exception e) {
|
throw e;
|
}
|
}
|
|
@Override
|
public Integer updateDeleteFlag(String userCode, String docCode) {
|
String sql = "set nocount on\n";
|
try {
|
sql += "declare @docCode varchar(200) ='" + docCode + "' \n";
|
sql += "update t482101H deleteFlag=1 where userCode =" + GridUtils.prossSqlParm(userCode) +
|
" and docCode in (select list from GetInStr(@docCode))\n";//标记删除
|
sql += " select @@ROWCOUNT";
|
return jdbcTemplate.queryForObject(sql, Integer.class);
|
} catch (Exception e) {
|
throw e;
|
}
|
}
|
|
@Override
|
public Integer deleteEmail(String userCode, String docCode) {
|
String sql = "set nocount on\n";
|
try {
|
sql += "declare @docCode varchar(200) ='" + docCode + "' \n";
|
sql += "delete t482101H where userCode =" + GridUtils.prossSqlParm(userCode) +
|
" and docCode in (select list from GetInStr(@docCode))\n";//标记删除
|
sql += " select @@ROWCOUNT";
|
return jdbcTemplate.queryForObject(sql, Integer.class);
|
} catch (Exception e) {
|
throw e;
|
}
|
}
|
|
@Override
|
public Integer deleteEmail(String messageId) {
|
String sql = "set nocount on\n";
|
try {
|
sql += "declare @messageId varchar(200) ='" + messageId + "' \n";
|
sql += "delete t482101H where messageId in (select list from GetInStr(@messageId))\n";//删除
|
sql += " select @@ROWCOUNT";
|
return jdbcTemplate.queryForObject(sql, Integer.class);
|
} catch (Exception e) {
|
throw e;
|
}
|
}
|
|
@Override
|
public t482101HEntity getReceivingMailInfo(String docCode) {
|
String sql = "set nocount on\n";
|
try {
|
sql += "select top 1 DocCode,companyId,companyName,sender,receiver,mailType,subject,content,plain_text,file_unid as fileUNID,messageId," +
|
"read_flag,delete_flag,attach_flag,urgent_flag,receipt_flag,track_flag,userCode,userName,create_time,update_time," +
|
"send_status,receive_time,sign_id,attachment_list,remark,remark,DocVersion from t482101H " +
|
"where docCode=" + GridUtils.prossSqlParm(docCode);
|
return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(t482101HEntity.class)).get(0);
|
} catch (Exception e) {
|
throw e;
|
}
|
}
|
|
@Override
|
public List<t482101HList> getReceivingMailList(String email, Integer mailType, boolean isNoRead, String userCode) {
|
String sql = "set nocount on\n";
|
try {
|
sql += "select companyId,companyName,mailType,DocCode,sender,receiver,subject,plain_text," +
|
"receive_time,update_time,create_time,sender,userCode,userName,folder_id,delete_Flag, " +
|
"read_Flag from t482101H ";
|
sql += " where userCode=" + GridUtils.prossSqlParm(userCode);
|
sql += " and isnull(read_flag,0) = " + (isNoRead ? 0 : 1);//0表示未读,1表示已读
|
sql += " and mailType=" + mailType;//0:草稿箱 1:收件箱 2:发件箱
|
if (StringUtils.isNotBlank(email)) {
|
if (mailType == 1) {
|
sql += " and receiver like '%" + email + "%'";
|
} else if (mailType == 2) {
|
sql += " and sender =" + GridUtils.prossSqlParm(email);
|
}
|
}
|
return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(t482101HList.class));
|
} catch (Exception e) {
|
throw e;
|
}
|
}
|
|
|
@Override
|
public List<t482101HEntity> getMailReceiving(T482102Entity emailEntity, HttpServletRequest request) throws MessagingException {
|
String imapServer = emailEntity.getReceiveHost();//"imap.qq.com";
|
String user = emailEntity.getEmail();//"xxx@qq.com";
|
String pwd = emailEntity.getPassword();//"xxxx";
|
|
HashMap IAM = new HashMap();
|
//带上IMAP ID信息,由key和value组成,例如name,version,vendor,support-email等。
|
IAM.put("name", emailEntity.getAliasEmail());
|
IAM.put("version", emailEntity.getDocVersion() + "");
|
IAM.put("vendor", emailEntity.getCompanyName());
|
IAM.put("support-email", emailEntity.getEmail());
|
//创建会话
|
Session session = Session.getInstance(new Properties(), new Authenticator() {
|
@Override
|
protected PasswordAuthentication getPasswordAuthentication() {
|
return new PasswordAuthentication(user, pwd);
|
}
|
});
|
//存储对象
|
IMAPStore store = (IMAPStore) session.getStore(emailEntity.getReceiveProtocol());//imap协议或pop3协议类型(推荐你使用IMAP协议来存取服务器上的邮件。)
|
//连接
|
store.connect(imapServer, user, pwd);
|
store.id(IAM);//163邮箱需要,不然会报:A3 NO SELECT Unsafe Login. Please contact kefu@188.com for help
|
Folder folder = null;
|
try {
|
// 获得收件箱
|
folder = store.getFolder("INBOX");
|
// 以读写模式打开收件箱
|
folder.open(Folder.READ_WRITE);
|
//false 表示未读
|
// FlagTerm flagTerm = new FlagTerm(new Flags(Flags.Flag.SEEN), true);
|
//获得收件箱的邮件列表(已读的,根据上面的flagTerm获取已读或未读)
|
// Message[] messages = folder.search(flagTerm);
|
//获取收件箱邮件(全部)
|
Message[] messages = folder.getMessages();
|
//返回邮箱封装内容
|
return setMailContent(messages, user, request);
|
} catch (NoSuchProviderException e) {
|
throw e;
|
} catch (MessagingException e) {
|
throw e;
|
} catch (IOException e) {
|
throw new RuntimeException(e);
|
} catch (Exception e) {
|
throw new RuntimeException(e);
|
} finally {
|
try {
|
if (folder != null) {
|
folder.close(false);
|
}
|
if (store != null) {
|
store.close();
|
}
|
} catch (MessagingException e) {
|
throw e;
|
}
|
}
|
}
|
|
|
@Override
|
public void sendingMail(t482101HEntity t482101H, HttpServletRequest request) throws Exception {
|
try {
|
//根据当前用户查询绑定的邮箱信息
|
T482102Entity emailEntity = emailAccountIfc.getAccountInfo(t482101H.getUserCode(), t482101H.getSender());//返回邮箱的账号信息
|
if (emailEntity == null || StringUtils.isBlank(emailEntity.getEmail())) {
|
if (StringUtils.isBlank(t482101H.getDocCode())) {
|
t482101H.setMailType(0);//草稿箱状态
|
t482101H = saveReceivingMail(t482101H);//保存到草稿箱内
|
}
|
throw new Exception("找不到邮箱:" + t482101H.getSender() + "配置信息请完善。邮件已保存到草稿箱#" + t482101H.getDocCode());
|
}
|
//有发送的邮件保存到后台数据库
|
//邮箱服务器配置
|
Properties properties = new Properties();
|
properties.setProperty("mail.smtp.host", emailEntity.getSmtpHost());
|
properties.setProperty("mail.smtp.port", emailEntity.getSmtpPort() + "");
|
properties.setProperty("mail.smtp.auth", "true");
|
properties.setProperty("mail.smtp.starttls.enable", "true");
|
//
|
String sendEmail = emailEntity.getEmail();//发件人
|
String sendPassword = emailEntity.getPassword();//密码
|
String recipientEmail = StringUtils.join(t482101H.getReceiver(), ",");//收件人
|
Session session = Session.getInstance(properties, new Authenticator() {
|
@Override
|
protected PasswordAuthentication getPasswordAuthentication() {
|
return new PasswordAuthentication(sendEmail, sendPassword);
|
}
|
});
|
|
MimeMessage message = new MimeMessage(session);
|
message.setFrom(new InternetAddress(sendEmail));
|
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail));
|
message.setSubject(t482101H.getSubject());
|
|
String Unique_ID = "<onBus_" + UUID.randomUUID().toString().toUpperCase() + "@mail.com>";//系统单号唯一码
|
message.setHeader("Message-ID", Unique_ID);//系统内部唯一码
|
t482101H.setMessageId(Unique_ID);//messageId赋值
|
|
if (t482101H.getCc() != null && t482101H.getCc().size() > 0) {//抄送
|
message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(StringUtils.join(t482101H.getCc(), ",")));
|
}
|
if (t482101H.getBcc() != null && t482101H.getBcc().size() > 0) {//密送
|
message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(StringUtils.join(t482101H.getBcc(), ",")));
|
}
|
|
//创建多部分消息
|
Multipart multipart = new MimeMultipart();
|
|
MimeBodyPart textPart = new MimeBodyPart();
|
textPart.setText(t482101H.getContent());//内容
|
multipart.addBodyPart(textPart);
|
|
//下面附件内容
|
if (StringUtils.isNotBlank(t482101H.getFileUNID())) {//有附件内容
|
//获取到附件内容
|
List<AttachmentEntity> attachmentEntities = getAttachmentEntityList(t482101H.getFileUNID());
|
if (attachmentEntities != null && attachmentEntities.size() > 0) {
|
for (AttachmentEntity a : attachmentEntities) {
|
InputStream inputStream = new ByteArrayInputStream(a.getOriginalPicture());
|
File file = new File(a.getOriginalFileName());
|
FileUtils.copyInputStreamToFile(inputStream, file);
|
MimeBodyPart bodyPart = new MimeBodyPart();
|
bodyPart.attachFile(file);
|
bodyPart.setFileName(a.getOriginalFileName());
|
multipart.addBodyPart(bodyPart);
|
}
|
}
|
}
|
message.setContent(multipart);
|
try {
|
if (StringUtils.isBlank(t482101H.getDocCode())) {//不在草稿箱有单号
|
saveReceivingMail(t482101H);//保存后发送
|
} else {
|
t482101H.setMailType(2);//发件箱状态
|
updateMailDrafts(t482101H);//更新成草稿箱
|
}
|
Transport.send(message);//发送
|
} catch (MessagingException m) {//发送异常处理
|
t482101H.setMailType(0);//草稿箱状态
|
updateMailDrafts(t482101H);//更新成草稿箱
|
throw new Exception("发送邮件异常,邮件已保存在草稿箱。异常原因:" + m.getCause() != null ? m.getCause().getMessage() : m.getMessage());
|
}
|
} catch (Exception e) {
|
throw e;
|
}
|
}
|
|
@Override
|
public Integer updateMailDrafts(t482101HEntity mail) {
|
String sql = "set nocount on\n";
|
try {
|
sql += "update t482101H set sender=" + GridUtils.prossSqlParm(mail.getSender()) + ",receiver=" + GridUtils.prossSqlParm(StringUtils.join(mail.getReceiver(), ",")) + "," +
|
"cc=" + GridUtils.prossSqlParm(StringUtils.join(mail.getCc(), ",")) + ",bcc=" + GridUtils.prossSqlParm(StringUtils.join(mail.getBcc(), ",")) + ",subject=" + GridUtils.prossSqlParm(mail.getSubject()) + "," +
|
"content=" + GridUtils.prossSqlParm(mail.getContent()) + ",file_unid=" + GridUtils.prossSqlParm(mail.getFileUNID()) + ",mailType=" + mail.getMailType() + "," +
|
"updateTime=getdate() \n";
|
sql += " where docCode=" + GridUtils.prossSqlParm(mail.getDocCode());
|
sql += " select @@ROWCOUNT";
|
return jdbcTemplate.queryForObject(sql, Integer.class);
|
} catch (Exception e) {
|
throw e;
|
}
|
}
|
|
// @Override
|
// public Integer deleteMailDrafts(String userCode, String docCode) {
|
// String sql = "set nocount on\n";
|
// try {
|
// sql += "declare @docCode varchar(200) ='" + docCode + "' \n";
|
// sql += "delete t482101H where userCode =" + GridUtils.prossSqlParm(userCode) +
|
// " and docCode in (select list from GetInStr(@docCode)) \n";
|
// sql += " select @@ROWCOUNT";
|
// return jdbcTemplate.queryForObject(sql, Integer.class);
|
// } catch (Exception e) {
|
// throw e;
|
// }
|
// }
|
|
/**
|
* 收件箱返回的信息进行封装处理
|
*
|
* @param messages
|
* @return
|
* @throws MessagingException
|
* @throws IOException
|
*/
|
public List<t482101HEntity> setMailContent(Message[] messages, String receiver, HttpServletRequest request) throws Exception {
|
try {
|
List<t482101HEntity> t482101HEntityList = new ArrayList<>();
|
HttpSession session = request.getSession();
|
List<String> messageIdList = getMessageIdList(receiver);
|
Message m = null;
|
List<String> deleteMsgId = new ArrayList<>();
|
for (int i = 0; i < messages.length; i++) {
|
m = messages[i];
|
String messageId = m.getHeader("Message-ID")[0];
|
if (messageIdList != null && messageIdList.contains(messageId)) {
|
if (m.isSet(Flags.Flag.DELETED)) {//邮件是否需要删除
|
deleteMsgId.add(messageId);//删除的
|
}
|
//已经存在就不需要再次封装处理
|
continue;
|
}
|
|
t482101HEntity mail = new t482101HEntity();
|
mail.setMessageId(messageId);//获取邮件唯一ID
|
mail.setMailType(1);//收件
|
if (m.isSet(Flags.Flag.SEEN)) {//邮件已标记为已读
|
mail.setReadFlag(1);//已读
|
}
|
if (m.isExpunged()) {//检查一个消息是否已被删除。
|
mail.setDeleteFlag(1);//已删除
|
}
|
if (m.isSet(Flags.Flag.ANSWERED)) {//邮件是否已回复
|
|
}
|
if (m.isSet(Flags.Flag.DRAFT)) {//是否是草稿箱
|
mail.setMailType(0);//是草稿箱
|
}
|
|
mail.setClassType(1);
|
mail.setUserCode((String) session.getAttribute(SessionKey.USERCODE));
|
mail.setUserName((String) session.getAttribute(SessionKey.USERNAME));
|
mail.setCompanyId((String) session.getAttribute(SessionKey.COMPANY_ID));
|
mail.setCompanyName((String) session.getAttribute(SessionKey.COMPANY_NAME));
|
mail.setSubject(m.getSubject());//标题
|
Date date = m.getReceivedDate();//时间
|
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
mail.setReceiveTime(formatter.format(date));
|
String result = "";
|
StringBuilder plainText = new StringBuilder();
|
if (m.isMimeType("text/plain")) {
|
plainText.append(m.getContent());
|
} else if (m.isMimeType("text/html")) {//html格式
|
result = m.getContent().toString();
|
} else if (m.isMimeType("multipart/*")) {
|
List<String> fileSeq = new ArrayList<>();
|
MimeMultipart mimeMultipart = (MimeMultipart) m.getContent();
|
String uuId = UUID.randomUUID().toString().toUpperCase();//生成uuid
|
result = getTextFromMimeMultipart(mimeMultipart, uuId, fileSeq, plainText, request);
|
if (fileSeq.size() > 0) {//有附件内容保存
|
mail.setFileUNID(uuId + ";" + StringUtils.join(fileSeq, ";"));
|
mail.setAttachFlag(1);//有附件
|
}
|
} else {
|
result = m.getContent().toString();
|
}
|
mail.setContent(result);//保存内容
|
mail.setPlainText(plainText.toString().trim());//明文
|
String from = MimeUtility.decodeText(m.getFrom()[0].toString());
|
InternetAddress internetAddress = new InternetAddress(from);
|
mail.setSender(internetAddress.getAddress());//发件人
|
from = MimeUtility.decodeText(m.getRecipients(Message.RecipientType.TO)[0].toString());
|
internetAddress = new InternetAddress(from);
|
// mail.setReceiver(internetAddress.getAddress());//收件人
|
List<String> receivers = new ArrayList<>();//抄送人
|
receivers.add(receiver);
|
mail.setReceiver(receivers);//统一成一个收件人
|
|
Address[] ccAddress = m.getRecipients(Message.RecipientType.CC);
|
if (ccAddress != null && ccAddress.length > 0) {
|
List<String> cc = new ArrayList<>();//抄送人
|
for (Address c : ccAddress) {
|
from = MimeUtility.decodeText(c.toString());
|
internetAddress = new InternetAddress(from);
|
cc.add(internetAddress.getAddress());
|
}
|
mail.setCc(cc);
|
}
|
Address[] bccAddress = m.getRecipients(Message.RecipientType.BCC);
|
if (bccAddress != null && bccAddress.length > 0) {
|
List<String> bcc = new ArrayList<>();//密送
|
for (Address c : bccAddress) {
|
from = MimeUtility.decodeText(c.toString());
|
internetAddress = new InternetAddress(from);
|
bcc.add(internetAddress.getAddress());
|
}
|
mail.setBcc(bcc);//密送人
|
}
|
t482101HEntityList.add(mail);
|
}
|
if (deleteMsgId.size() > 0) {
|
//删除
|
deleteEmail(StringUtils.join(deleteMsgId, ","));
|
}
|
return t482101HEntityList;
|
} catch (Exception e) {
|
throw e;
|
}
|
}
|
|
// 辅助方法,用于递归获取纯文本邮件内容
|
private String getTextFromMimeMultipart(MimeMultipart mimeMultipart, String uuId, List<String> fileSeq, StringBuilder plainText, HttpServletRequest request) throws Exception {
|
int count = mimeMultipart.getCount();
|
if (count == 0) {
|
throw new MessagingException("Multipart with no body parts");
|
}
|
boolean multipartAlternative = isMultipartAlternative(mimeMultipart);
|
StringBuilder result = new StringBuilder();
|
if (multipartAlternative) {
|
for (int i = 0; i < count; i++) {
|
BodyPart bodyPart = mimeMultipart.getBodyPart(i);
|
if (bodyPart.isMimeType("text/plain")) {//这个是获取纯文本
|
plainText.append(bodyPart.getContent());
|
}
|
if (bodyPart.isMimeType("text/html")) {//这个是获取html格式
|
result.append(bodyPart.getContent());
|
}
|
}
|
} else {
|
for (int i = 0; i < count; i++) {
|
BodyPart bodyPart = mimeMultipart.getBodyPart(i);
|
if (bodyPart.isMimeType("image/*")) {//图片
|
String nextResult = result.toString();
|
String unIdPath = saveFileAndImage(bodyPart, "image", uuId, request);
|
String cId = ((IMAPBodyPart) bodyPart).getContentID();//获取cId
|
if (nextResult.contains(cId) && StringUtils.isNotBlank(unIdPath)) {//有嵌套内容
|
nextResult = nextResult.replace("cid:" + cId + "", unIdPath);//替换
|
result.setLength(0);//清空先
|
result.append(nextResult);
|
}
|
} else if (Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {//附件
|
fileSeq.add(saveFileAndImage(bodyPart, Part.ATTACHMENT, uuId, request));
|
} else if (bodyPart.isMimeType("multipart/*")) {
|
result.append(getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent(), uuId, fileSeq, plainText, request));
|
}
|
}
|
}
|
return result.toString();
|
}
|
|
// 辅助方法,判断是否为multipart/alternative类型的邮件
|
private boolean isMultipartAlternative(MimeMultipart mimeMultipart) throws Exception {
|
boolean textPlainFound = false;
|
boolean textHtmlFound = false;
|
int count = mimeMultipart.getCount();
|
for (int i = 0; i < count; i++) {
|
BodyPart bodyPart = mimeMultipart.getBodyPart(i);
|
if (bodyPart.isMimeType("text/plain")) {
|
textPlainFound = true;
|
} else if (bodyPart.isMimeType("text/html")) {
|
textHtmlFound = true;
|
}
|
}
|
return textPlainFound && textHtmlFound;
|
}
|
|
private String saveFileAndImage(BodyPart bodyPart, String type, String unId, HttpServletRequest request) throws Exception {
|
try {
|
String fileName = MimeUtility.decodeText(bodyPart.getFileName());
|
if (type.equals("image")) {
|
String pattern = ".*\\.(jpg|jpeg|png|gif)$";
|
fileName = Pattern.matches(pattern, fileName) ? fileName : fileName + ".jpg";
|
}
|
File file = new File(fileName);
|
FileUtils.copyInputStreamToFile(bodyPart.getInputStream(), file);
|
AttachmentEntity attachmentEntity = new AttachmentEntity();
|
attachmentEntity.setDoccode("");
|
attachmentEntity.setRowId("");
|
attachmentEntity.setFormId(482101);
|
attachmentEntity.setUnid(unId);
|
attachmentEntity.setSeq(null);
|
attachmentEntity.setFieldId("file");
|
attachmentEntity.setPhysicalFile(file.getName());
|
attachmentEntity.setOriginalFileName(file.getName());
|
AttachmentIfc attachmentIfc = (AttachmentIfc) FactoryBean.getBean("AttachmentImpl");
|
//保存附件
|
AttachmentWhereEntity attachmentWhereEntity = attachmentIfc.saveAttachment(attachmentEntity, file, "2");
|
if (type.equals("image")) {
|
//输出 url
|
// return imgData.getImageUrl(attachmentWhereEntity.getUnid() + ";" + attachmentWhereEntity.getSeq(), null,
|
// null, true, true, null);
|
DataSourceEntity dataSourceEntity = MultiDataSource.getDataSourceMap(request);
|
return shoppingImageServer + "/uploads/attachment/" + dataSourceEntity.getDbId() + "/482101/" + attachmentWhereEntity.getUnid() + "@p@" + attachmentWhereEntity.getSeq() + ".jpg";
|
} else if (type.equals(Part.ATTACHMENT)) {
|
return attachmentWhereEntity.getSeq() + "";
|
} else {
|
return null;
|
}
|
} catch (Exception e) {
|
throw e;
|
}
|
}
|
|
@Override
|
public List<AttachmentEntity> getAttachmentEntityList(String unIdSeq) {
|
String unId = null;
|
if (StringUtils.isBlank(unIdSeq)) {
|
return null;
|
}
|
String[] array = unIdSeq.split(";");
|
unId = array[0];//在有值时候第一个必定是unId
|
ArrayList<String> seqs = new ArrayList<>(Arrays.asList(array));
|
seqs.remove(0);//去掉第一个元素(UNID)
|
String sql = " set nocount on \n"
|
+ " declare @unid varchar(50) = " + GridUtils.prossSqlParm(unId) + " \n";
|
sql += " select UNID,seq,DocCode,RowId,FieldId,FormId, \n"
|
+ " PhysicalPath,PhysicalFile,OriginalFileName,FileSize,FileType, \n"
|
+ " AuthorCode,AuthorName,SmallPicPath,UploadTime,OriginalPicture \n"
|
+ " from _sys_Attachment \n"
|
+ " where unid = @unid ";
|
if (seqs.size() > 0) {
|
sql += " and seq in(" + StringUtils.join(seqs, ",") + ")\n";
|
}
|
List<Map<String, Object>> list = this.jdbcTemplate.queryForList(sql);
|
List<AttachmentEntity> attachmentList = new ArrayList<AttachmentEntity>();
|
for (int i = 0; list != null && i < list.size(); i++) {
|
AttachmentEntity attachment = new AttachmentEntity();
|
attachment.setOriginalFileName(list.get(i).get("OriginalFileName") == null ? null : (String) list.get(i).get("OriginalFileName"));
|
//附件处理
|
attachment.setOriginalPicture(list.get(i).get("OriginalPicture") == null ? null : (byte[]) list.get(i).get("OriginalPicture"));
|
attachmentList.add(attachment);
|
}
|
return attachmentList;
|
}
|
|
@Override
|
public List<String> getMessageIdList(String receiver) {
|
List<String> messageId = null;
|
String sql = " set nocount on \n";
|
try {
|
sql += "select messageId from t482101H where receiver='" + receiver + "'";
|
List<t482101HEntity> message = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(t482101HEntity.class));
|
if (message != null && message.size() > 0) {
|
messageId = new ArrayList<>();
|
messageId = message.stream().map(t482101HEntity::getMessageId).distinct().collect(Collectors.toList());//去重
|
}
|
return messageId;
|
} catch (Exception e) {
|
throw e;
|
}
|
}
|
|
@Override
|
public void updateRead(String docCode) {
|
String sql = " set nocount on \n";
|
try {
|
sql += "declare @docCode varchar(200) ='" + docCode + "' \n";
|
sql += "update t482101H set read_flag=1 where docCode in (select list from GetInStr(@docCode))\n";
|
sql += "select @@ROWCOUNT";
|
jdbcTemplate.queryForObject(sql, Integer.class);
|
} catch (Exception e) {
|
throw e;
|
}
|
}
|
}
|