初始化邮箱同步方法
continuous-integration/drone/push Build is passing Details

于相涌/mail
YXY 2 years ago
parent 592bf3dcbf
commit 2daa1d5faf

@ -10,7 +10,8 @@ public enum AppType {
* *
*/ */
MULTIDIMENSIONAL_TABLE("MULTIDIMENSIONAL_TABLE", "多维表格"), MULTIDIMENSIONAL_TABLE("MULTIDIMENSIONAL_TABLE", "多维表格"),
APPROVAL_TASK("APPROVAL_TASK", "审批回调"); APPROVAL_TASK("APPROVAL_TASK", "审批回调"),
SYNC_EMAIL("SYNC_EMAIL", "同步邮箱");
private final String code; private final String code;
private final String info; private final String info;

@ -11,10 +11,12 @@ import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import javax.mail.Flags; import javax.mail.*;
import javax.mail.Message;
import javax.mail.internet.InternetAddress; import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility; import javax.mail.internet.MimeUtility;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -33,23 +35,28 @@ public class MailHelper {
private EventLogMapper eventLogMapper; private EventLogMapper eventLogMapper;
protected void parseMsg(Message[] messages,LarkTableRequest add) { protected void parseMsg(Message[] messages,LarkTableRequest add) {
log.info("------------------------开始解析邮件----------------------------------");
/** /**
* *
*/ */
List<EventLog> logs = new ArrayList<>(); List<EventLog> logs = new ArrayList<>();
for (Message message : messages) { for (Message message : messages) {
String msgSubject = null;
try { try {
System.out.println("消息:" + message.getSubject()); log.info("----------------------------------------------------------");
String from = MimeUtility.decodeText(message.getFrom()[0].toString()); String from = MimeUtility.decodeText(message.getFrom()[0].toString());
InternetAddress internetAddress = new InternetAddress(from); InternetAddress internetAddress = new InternetAddress(from);
System.out.println("发件人:" + internetAddress.getPersonal() + '(' + internetAddress.getAddress() + ')'); msgSubject = String.format("主题:%s,发件人:%s(%s),收件人:%s",
message.getSubject(),
internetAddress.getPersonal(),
internetAddress.getAddress(),
this.getReceiveAddress(message,null));
String recordId = syncLarkTable(message,add); String recordId = syncLarkTable(message,add);
this.buildLog(logs,message,recordId,null); this.buildLog(logs,msgSubject,recordId,null);
message.setFlag(Flags.Flag.SEEN, true); message.setFlag(Flags.Flag.SEEN, true);
} catch (Exception e) { } catch (Exception e) {
this.buildLog(logs,message,null,e); this.buildLog(logs,msgSubject,null,e);
} }
} }
if (CollectionUtils.isNotEmpty(logs)){ if (CollectionUtils.isNotEmpty(logs)){
@ -57,22 +64,62 @@ public class MailHelper {
} }
} }
private void buildLog(List<EventLog> logs,Message message,String recordId,Exception e){ public String getReceiveAddress(Message msg, Message.RecipientType type) throws MessagingException {
EventLog log = e != null ? StringBuffer receiveAddress = new StringBuffer();
new EventLog(null, EventOperateType.SYNC_MAIL.getCode(), message.toString()) Address[] addresss = null;
: new EventLog(null, EventOperateType.SYNC_MAIL.getCode(), message.toString(),null,e.getMessage()); if (type == null) {
addresss = msg.getAllRecipients();
} else {
addresss = msg.getRecipients(type);
}
if (addresss == null || addresss.length < 1)
return null;
for (Address address : addresss) {
InternetAddress internetAddress = (InternetAddress) address;
receiveAddress.append(internetAddress.toUnicodeString()).append(",");
}
receiveAddress.deleteCharAt(receiveAddress.length() - 1); //删除最后一个逗号
return receiveAddress.toString();
}
public void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException {
//如果是文本类型的附件通过getContent方法可以取到文本内容但这不是我们需要的结果所以在这里要做判断
boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;
if (part.isMimeType("text/*") && !isContainTextAttach) {
content.append(part.getContent().toString());
} else if (part.isMimeType("message/rfc822")) {
getMailTextContent((Part) part.getContent(), content);
} else if (part.isMimeType("multipart/*")) {
Multipart multipart = (Multipart) part.getContent();
int partCount = multipart.getCount();
for (int i = 0; i < partCount; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
getMailTextContent(bodyPart, content);
}
}
}
private void buildLog(List<EventLog> logs,String message,String recordId,Exception e){
EventLog log = e == null ?
new EventLog(null, EventOperateType.SYNC_MAIL.getCode(), message)
: new EventLog(null, EventOperateType.SYNC_MAIL.getCode(), message,null,e.getMessage());
log.setRemark(recordId); log.setRemark(recordId);
logs.add(log); logs.add(log);
} }
private String syncLarkTable(Message message,LarkTableRequest add){ private String syncLarkTable(Message message,LarkTableRequest add) throws MessagingException, IOException {
Map<String, Object> body = this.buildBody(message); StringBuffer content = new StringBuffer(30);
getMailTextContent(message,content);
Map<String, Object> body = this.buildBody(message,content.toString());
add.setBody(body); add.setBody(body);
CreateAppTableRecordRespBody respBody = larkTableHelper.addTableRecord(add); CreateAppTableRecordRespBody respBody = larkTableHelper.addTableRecord(add);
return respBody.getRecord().getRecordId(); return respBody.getRecord().getRecordId();
} }
protected Map<String,Object> buildBody(Message message){ protected Map<String,Object> buildBody(Message message,String content){
return new HashMap<>(); return new HashMap<>();
} }

@ -10,6 +10,8 @@ import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility; import javax.mail.internet.MimeUtility;
import javax.mail.search.FlagTerm; import javax.mail.search.FlagTerm;
import java.security.Security; import java.security.Security;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties; import java.util.Properties;
/** /**
@ -23,43 +25,17 @@ public class MailHttpHelper extends MailHelper{
public static void main(String[] args) { public static void main(String[] args) {
MailHttpHelper mailHelper = new MailHttpHelper(); MailHttpHelper mailHelper = new MailHttpHelper();
MailRequest req = new MailRequest("xjia.synology.me",5000,"xjzsb","12345678"); MailRequest req = new MailRequest("xjia.synology.me",5000,"xjzsb","12345678");
// req = new MailRequest("imap.qq.com",993,"932687738","lwoapikuenmzbfaj"); req = new MailRequest("xjia.synology.me",143,"xjzsb@xjia-edu.com","12345678");
mailHelper.test(req); mailHelper.receiveMail(req,null);
}
public void test(MailRequest req){
try {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties props = new Properties();
props.setProperty("mail.debug","true");
// props.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
// props.setProperty("mail.pop3.socketFactory.fallback", "false");
props.setProperty("mail.transport.protocol", "pop3");
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(req.getUserName(),req.getAuthorizationCode());
}
});
Store store = session.getStore("pop3");
store.connect(req.getEmailServer(),req.getEmailPort(),req.getUserName(), req.getAuthorizationCode());
Folder inbox = store.getFolder("INBOX");
}catch (Exception e){
log.info("",e);
}
} }
public void receiveMail(MailRequest req, LarkTableRequest add){ public void receiveMail(MailRequest req, LarkTableRequest add){
// 定义连接imap服务器的属性信息 // 定义连接imap服务器的属性信息
String portStr = String.valueOf(req.getEmailPort());
Properties props = new Properties(); Properties props = new Properties();
props.setProperty("mail.smtp.ssl.enable","false"); props.put("mail.store.protocol", req.getEmailProtocol());
props.setProperty("mail.imap.starttls.enable","true"); props.put("mail.imap.host", req.getEmailServer());
props.setProperty("mail.imap.socketFactory.fallback", "false"); props.put("mail.imap.port", req.getEmailPort());
props.setProperty("mail.transport.protocol", req.getEmailProtocol()); props.put("mail.imap.starttls.enable", "true");
props.setProperty("mail.imap.port", portStr);
props.setProperty("mail.imap.socketFactory.port", portStr);
props.setProperty("mail.debug","false");
//创建会话 //创建会话
Session session = Session.getInstance(props, new Authenticator() { Session session = Session.getInstance(props, new Authenticator() {
@Override @Override
@ -79,7 +55,7 @@ public class MailHttpHelper extends MailHelper{
// 以读写模式打开收件箱 // 以读写模式打开收件箱
folder.open(Folder.READ_WRITE); folder.open(Folder.READ_WRITE);
//false 表示未读 //false 表示未读
FlagTerm flagTerm = new FlagTerm(new Flags(Flags.Flag.SEEN),false); FlagTerm flagTerm = new FlagTerm(new Flags(Flags.Flag.SEEN),true);
//获得收件箱的邮件列表 //获得收件箱的邮件列表
Message[] messages = folder.search(flagTerm); Message[] messages = folder.search(flagTerm);
// 打印不同状态的邮件数量 // 打印不同状态的邮件数量
@ -88,8 +64,7 @@ public class MailHttpHelper extends MailHelper{
folder.getUnreadMessageCount(), folder.getUnreadMessageCount(),
folder.getNewMessageCount(), folder.getNewMessageCount(),
folder.getDeletedMessageCount()); folder.getDeletedMessageCount());
log.info("------------------------开始解析邮件----------------------------------"); this.parseMsg(messages,add);
// this.parseMsg(messages,add);
} catch (Exception e) { } catch (Exception e) {
log.error("邮件解析失败",e); log.error("邮件解析失败",e);
} finally { } finally {
@ -105,4 +80,28 @@ public class MailHttpHelper extends MailHelper{
} }
} }
} }
/**
*
*/
@Override
protected Map<String, Object> buildBody(Message message,String content) {
Map<String, Object> map = new HashMap<>();
map.put("学生姓名",null);
map.put("意向度",null);
map.put("现有学历",null);
map.put("报名时间",null);
map.put("手机号码",null);
map.put("省市",null);
map.put("备注",null);
map.put("回放记录",null);
map.put("业务员",null);
map.put("信息完成度",null);
map.put("数据来源",null);
map.put("目标国家",null);
map.put("所属学校",null);
map.put("邮箱来源",null);
map.put("原始线索",content);
return map;
}
} }

@ -63,6 +63,6 @@ public interface LarkTableRelationMapper
*/ */
public int deleteLarkTableRelationByIds(Long[] ids); public int deleteLarkTableRelationByIds(Long[] ids);
public List<LarkCompanyTableInfo> queryListByIdListJoinLarkCompany(@Param("ids") List<Long> tableIds, @Param("flag") Long flag, @Param("relationType") String relationType); public List<LarkCompanyTableInfo> queryListByIdListJoinLarkCompany(@Param("tableIds") List<Long> tableIds, @Param("flag") Long flag, @Param("relationType") String relationType);
} }

@ -2,7 +2,7 @@
<!DOCTYPE mapper <!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ruoyi.flyingbook.mapperMailInfoMapper"> <mapper namespace="com.ruoyi.flyingbook.mapper.MailInfoMapper">
<resultMap type="com.ruoyi.flyingbook.domain.MailInfo" id="MailInfoResult"> <resultMap type="com.ruoyi.flyingbook.domain.MailInfo" id="MailInfoResult">
<result property="id" column="id" /> <result property="id" column="id" />

@ -97,7 +97,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter
// 过滤请求 // 过滤请求
.authorizeRequests() .authorizeRequests()
// 对于登录login 验证码captchaImage 允许匿名访问 // 对于登录login 验证码captchaImage 允许匿名访问
.antMatchers("/login", "/captchaImage", "/approval", "/approval2").anonymous() .antMatchers("/login", "/captchaImage", "/approval","/syncEmail", "/approval2").anonymous()
.antMatchers( .antMatchers(
HttpMethod.GET, HttpMethod.GET,
"/*.html", "/*.html",

@ -0,0 +1,24 @@
package com.ruoyi.quartz.controller;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.quartz.task.MailSyncTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
public class MailInfoController extends BaseController {
@Autowired
private MailSyncTask mailSyncTask;
@PostMapping("/syncEmail")
public void syncEmail() {
mailSyncTask.syncMail();
}
}
Loading…
Cancel
Save