package com.mw.utils;

import com.mw.bean.SmsAlarmLogBean;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.search.FlagTerm;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern; /**
*
*/
public class MonitorMail { public static final String prefix ="[";
public static final String suffix ="]"; public static final String regex="\\[([^}]*)\\]";
public Pattern pattern = Pattern.compile(regex);
//邮箱服务地址
private String host;
//邮箱协议(pop3 imap,协议需要小写)
private String protocol;
//服务端口
private int port;
//邮箱name
private String username;
//邮箱密码
private String password; private URLName url; private Session session; private Store store; private Boolean filter; private Folder folder; private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); /**
*
* @param protocol 协议
* @param host 服务器
* @param port 端口
* @param username 邮箱账号
* @param password 邮箱密码
*/
public MonitorMail(String protocol,String host,int port,String username,String password){ //协议小写
this.protocol=protocol.toLowerCase();
this.host=host;
this.port=port;
this.username=username;
this.password=password; } /**
* 初始化连接邮箱服务器
* @return
* @throws Exception
* store.isConnected();
*/ public MonitorMail initConnect() throws NoSuchProviderException,MessagingException{
//INBOX 为抓取收件箱的邮件
this.url = new URLName(protocol, host, port, "INBOX", username, password);
Properties props = new Properties();
props.put("mail.imap.timeout",4000);
props.put("mail.imap.connectiontimeout",4000);//连接超时时间
this.session = Session.getInstance(props, null);
//得到邮件仓库
this.store = session.getStore(url);
//连接server
this.store.connect(); return this; } /**
* 获取收件箱所有的信息消息
* @return
* @throws Exception
*/
public Message[] requireMessage() throws Exception{
this.folder = store.getFolder(url);
folder.open(Folder.READ_WRITE);
//index 索引
FlagTerm ft =
new FlagTerm(new Flags(Flags.Flag.SEEN), false); //false代表未读,true代表已读
Message[] message = folder.search(ft);
return message; } /**
* 获取邮箱内容
* @return
* @throws Exception
*/
public List<String> requireText(boolean filter) throws Exception{
this.filter=filter;
ArrayList<String> candidate =new ArrayList<>();
//获取邮箱内容对象
Message[] message = requireMessage(); for(int i=0;i<message.length;i++){
String text="";
//文本类型mail
if (message[i].isMimeType("text/plain")) { text = message[i].getContent().toString();
//媒体类型
}else if(message[i].isMimeType("multipart/*")){
text = requireMultipartContext(message[i]);
} //默认拦截器过滤mail 内容
if(filter){
String filterContent = defaultFilter(text);
if(filterContent!=null){
candidate.add(filterContent);
updateState(message[i]);
}
}else {
String filterContent = customerFilter(text);
candidate.add(filterContent);
updateState(message[i]);
} }
/**
System.out.println("发件人:" + formatAddress(message.getFrom())
+ "\n发送时间:" + formatDate(message.getSentDate())
+ "\n收件人:" + formatAddress(message.getRecipients(Message.RecipientType.TO))
// + "\n收件时间:" + formatDate(msg.getReceivedDate())
// + "\n抄送:" + formatAddress(msg.getRecipients(Message.RecipientType.CC))
// + "\n暗送:" + formatAddress(msg.getRecipients(Message.RecipientType.BCC))
+ "\n主题:" + message.getSubject());
**/ return candidate;
} protected void updateState(Message msg) throws Exception{
if(protocol.equals("imap")) {
//pop3没有判断邮件是否为已读的功能,要使用imap才可以进行邮件的标记状态
msg.setFlag(Flags.Flag.SEEN, true);//设置邮件为已读状态
// msg.saveChanges();
}
} /**
* 获取Multipart/*类型的邮箱内容
* @param message
* @return
*/
public String requireMultipartContext(Message message) throws Exception{
StringBuffer strBuf =new StringBuffer();
if (message.isMimeType("multipart/*")) {
Multipart mp = (Multipart) message.getContent();
int count = mp.getCount();
for (int j = 0; j < count; j++) {
BodyPart bp = mp.getBodyPart(j);
String disposition = bp.getDisposition();
if (disposition != null && disposition.equals(Part.ATTACHMENT)) {
System.out.println("附件:" + bp.getFileName());
} else {
if (bp.isMimeType("text/plain")) {
//邮件文本内容
strBuf.append(bp.getContent()); }
}
}
}
return strBuf.toString();
} /**
* 默认拦截,匹配"[][][][]" 此类型格式的mail
* @param mailContent
* @return 匹配失败返回null
*/
protected String defaultFilter(String mailContent){
StringBuffer buffer =new StringBuffer();
Matcher matcher = pattern.matcher(mailContent);
while(matcher.find()){
buffer.append(matcher.group());
}
String content = buffer.toString();
if(content.length()==0){
return null;
}
return content;
} /**
* 解析mail 内容
* @param content
* @return
*/
public SmsAlarmLogBean defaultParseText(String content){
if(!filter){
throw new IllegalStateException("只可以解析[][][]格式的邮件内容");
}
String[] info = content.split(suffix);
SmsAlarmLogBean alarm =null;
if(info.length>7){
alarm= new SmsAlarmLogBean();
alarm.setAlarm_type(preIndex(info[5]));
alarm.setServer_name(preIndex(info[0]));
alarm.setPc_ip(preIndex(info[1]));
alarm.setStart_time(preIndex(info[3]));
alarm.setProcess_name(preIndex(info[7]));
alarm.setEquip_name(preIndex(info[4])); }
return alarm;
} /**
* 自定义拦截器
*/
public String customerFilter(String mailContent){ return mailContent;
} /**
* 自定义解析
* @param content
* @return
*/
public Object customerParseText(String content){
return null;
} public static String preIndex(String info){
String substring ="";
if(info.length()>=2) {
substring= info.substring(1);
}
return substring;
} public void close()throws Exception{
if(folder !=null) {
if (folder.isOpen()) {
folder.close(true);
}
};
if(store!=null){
if(store.isConnected()){
store.close();
}
} } public static String formatDate(Date date) {
return sdf.format(date);
} public static String formatAddress(Address[] addr) {
StringBuffer sb = new StringBuffer();
if (addr == null) {
return "";
}
for (int i = 0; i < addr.length; i++) {
Address a = addr[i];
if (a instanceof InternetAddress) {
InternetAddress ia = (InternetAddress) a;
sb.append(ia.getPersonal() + "<" + ia.getAddress() + ">,");
} else {
sb.append(a.toString());
}
}
if (sb.length() != 0) {
return sb.substring(0, sb.length() - 1);
}
return "";
} //test MonitorMail
public static void main(String[] args) throws Exception {
MonitorMail mail =new MonitorMail("imap","192.168.0.101",143,"test@luobin.com",
"Pass1234");
List<String> strings = mail.initConnect().requireText(true);//fasle返回我们自定义的,根据业务需求
System.out.println(strings);
mail.close(); } }

java mail 接收邮件的更多相关文章

  1. 关于java mail 发邮件的问题总结(转)

    今天项目中有需要用到java mail发送邮件的功能,在网上找到相关代码,代码如下: import java.io.IOException; import java.util.Properties; ...

  2. java来接收邮件并解析邮件正文中的表格

    这里是实际需求中的一个DEMO 有一部分内容进行了注释和处理,参考需要修改成自己的实际参数.另这个是对于实际一个场景的案例并不是通用解决的工具类. import org.jsoup.Jsoup; im ...

  3. java mail 读取邮件列表,

    // 准备连接服务器的会话信息 Properties props = new Properties(); props.setProperty("mail.store.protocol&quo ...

  4. 关于使用Java Mail发邮件的问题

    今天做东西的时候突然遇到需要发邮件的问题,然后就使用SMTP协议进行邮件的发送.用了一个工具类简化邮件发送的功能, 在这次试验中,我使用了自己的QQ邮箱进行发送邮件的发送者. public class ...

  5. Java邮件服务学习之三:邮箱服务客户端-Java Mail

    一.java mail的两个JAR包 1.mail.jar:不在JDK中,核心功能依赖JDK4及以上,该jar包已经加入到java EE5: 下载地址:http://www.oracle.com/te ...

  6. java mail

    java mail 1.配置 mvn <dependency> <groupId>javax.mail</groupId> <artifactId>ma ...

  7. 基于java mail实现简单的QQ邮箱发送邮件

    刚学习到java邮件相关的知识,先写下这篇博客,方便以后翻阅学习. -----------------------------第一步 开启SMTP服务 在 QQ 邮箱里的 设置->账户里开启 S ...

  8. 通过Java发送邮件和接收邮件的工具类

    一.第一种 使用SMTP协议发送电子邮件 第一步:加入mail.jar包 (1)简单类型 package com.souvc.mail; import java.util.Date; import j ...

  9. Java Mail(二):JavaMail介绍及发送一封简单邮件

    http://blog.csdn.net/ghsau/article/details/17839983 ************************************************ ...

随机推荐

  1. C语言排序算法学习笔记——选择类排序

    选择排序:每一趟(例如第i趟)在后面n-i+1(i=1,2,3,……,n-1)个待排序元素中选取关键字最小的元素,作为有序子序列的第i个元素,直到n-1趟做完,待排序元素只剩下1个,就不用再选了. 简 ...

  2. C# 获取指定路径下的文件结构(树形结构)

    namespace Vue.Content { public class FileNames { public int id { get; set; } public string text { ge ...

  3. MindFusion 中节点关键路径的遍历

    工作中总能遇到 一些 奇葩的需求,提出这些奇葩需求的人,多半也是奇葩的人,要么不懂相关的计算机软件知识,要么就是瞎扯蛋,异想天开,然而这些奇葩的需求,我也总能碰到.言规正传,在一次项目中,使用了 Mi ...

  4. springboot学习三:整合jsp

    在pom.xml加入jstl <!--springboot tomcat jsp 支持开启--> <dependency> <groupId>org.apache. ...

  5. springcloud相关资料收集

    http://springboot.fun/  Spring  Boot 中文索引 http://springcloud.fun/   Spring Cloud 中文索引 https://spring ...

  6. windowNoTitle 无效

    在开发Dialog 时候如采用 Dialog Activity 方式可能会出现取消标题栏失效 以下针对两种情况说明 1.如果 extends AppCompatActivity 需要在setConte ...

  7. python远程执行dos命令

    https://blog.csdn.net/huaihuaidexiao/article/details/5543240 https://blog.csdn.net/bcbobo21cn/articl ...

  8. PHP SoapClient 调用与鉴权,以及对Java和C# 的webservice的兼容处理

    SoapClient使用注意事项: 第一要加上 cache_wsdl参数,以防服务器调用的是缓存的wsdl文件 然后是参数传递,如果是使用PHP自己写的WebService,参数传递按正常方式即可 1 ...

  9. python_练习04

    选课系统 角色:学校.学员.课程.讲师 要求: 1.创建北京.上海2所学校 2.创建linux.python.go3个课程,linux.python在北京开,go在上海开3.课程包含,周期,价格,通过 ...

  10. mount命令和自动挂载实例

    前言 介绍mount命令和一个实例. mount命令 作用 作用:挂载linux系统外的文件 命令格式 mount [-hV] mount -a [-fFnrsvw] [-t vfstype] mou ...