AnalysisYxyMail.java
10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
package com.espeed.tool;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.crypto.CipherInputStream;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import sun.misc.BASE64Decoder;
import com.espeed.pojo.YxySendMailMasterBase;
/***
*
* @author xieyong
* 邮件解析
*/
public class AnalysisYxyMail {
private MimeMessage msg;
private StringBuffer bodyText=new StringBuffer();
public String attrName="";
public String context="";
String servicepath="";
//定义结果集
List<String> result=new ArrayList<String>();
//解析邮件(本地)
public List ParseEmlMethod(YxySendMailMasterBase master,String emlpath)throws Exception{
//定义结果集
List<String> result=new ArrayList<String>();
//项目路径
servicepath = this.getClass().getClassLoader().getResource("/").getPath();
servicepath = servicepath.substring(1, servicepath.length());
servicepath = servicepath.replace("/WEB-INF/classes/","");
String emlFilePath=master.getEml_file_path().replace("#####", emlpath);
//判断是否之前的有加密的key
if(master.getEml_encode_key()!=null&&!master.getEml_encode_key().equals("")){
//解密邮件
BASE64Decoder enc=new BASE64Decoder();
//需要一个流 给它解密的流
CipherInputStream CStream = null;
CStream =(CipherInputStream) Encrypt.decrypt(emlFilePath,Encrypt.toKey(enc.decodeBuffer(master.getEml_encode_key())));
Session mailSession = Session.getDefaultInstance(System.getProperties(), null);
msg = new MimeMessage(mailSession, CStream);
}else{//未加密的
InputStream is =new FileInputStream(emlFilePath);
Session mailSession = Session.getDefaultInstance(System.getProperties(), null);
msg = new MimeMessage(mailSession, is);
is.close();
}
//获取内容
getMailContent((Part) msg);
context=bodyText+"";
//解析附件与图片
saveAttachMent((Part) msg,master);
result.add(attrName);
result.add(context);
return result;
}
//解析邮件(webservice)
public List ParseEmlWebService(YxySendMailMasterBase master,String emlcode)throws Exception{
//定义结果集
List<String> result=new ArrayList<String>();
//字符串转流
InputStream is = new ByteArrayInputStream(emlcode.getBytes());
Session mailSession = Session.getDefaultInstance(System.getProperties(), null);
msg = new MimeMessage(mailSession, is);
is.close();
//获取内容
getMailContent((Part) msg);
context=bodyText+"";
//解析附件与图片
saveAttachMent((Part) msg,master);
result.add(attrName);
result.add(context);
return result;
}
//获取内容
public void getMailContent(Part part) throws Exception {
String contenttype = part.getContentType();
String pageEcoding="GBK";
if(contenttype!=null&&contenttype!=""&&contenttype.indexOf("charset")!=-1){
int begin=contenttype.indexOf("charset=");
pageEcoding=contenttype.substring(begin+8).replaceAll("\"", "");
}
if(!pageEcoding.toLowerCase().equals("utf-8")
&&!pageEcoding.toLowerCase().equals("gbk")
&&!pageEcoding.toLowerCase().equals("iso-8859-1")
&&!pageEcoding.toLowerCase().equals("big5")
&&!pageEcoding.toLowerCase().equals("windows-1251")){
pageEcoding="GBK";
}
if(pageEcoding.equals("gb2312")){
pageEcoding="GBK";
}
int nameindex = contenttype.indexOf("name");
boolean conname = false;
if (nameindex != -1)
conname = true;
if (part.isMimeType("text/html") && !conname) {
if(!bodyText.toString().equals("")){
bodyText=new StringBuffer();
}
BufferedReader bis =null;
bis= new BufferedReader(new InputStreamReader(part.getInputStream(),pageEcoding));
StringBuffer context=new StringBuffer();
String line = null;
while ((line = bis.readLine()) != null) {
context.append(line);
}
bodyText.append(context);
}else if(part.isMimeType("text/plain") && !conname){
BufferedReader bis =null;
bis= new BufferedReader(new InputStreamReader(part.getInputStream(),pageEcoding));
StringBuffer context=new StringBuffer();
String line = null;
while ((line = bis.readLine()) != null) {
context.append(line);
}
bodyText.append(context);
}else if (part.isMimeType("multipart/*")) {
Multipart multipart = (Multipart) part.getContent();
int counts = multipart.getCount();
for (int i = 0; i < counts; i++) {
getMailContent(multipart.getBodyPart(i));
}
} else if (part.isMimeType("message/rfc822")) {
getMailContent((Part) part.getContent());
} else {
}
}
//解析附件与图片
public void saveAttachMent(Part part,YxySendMailMasterBase master)throws Exception{
String fileName = "";//文件名
boolean isPic=false;
String [] contentid=null;//是否有图片ID
if(part.isMimeType("multipart/*")){
Multipart mp = (Multipart) part.getContent();
for(int i=0;i<mp.getCount();i++){
BodyPart mpart = mp.getBodyPart(i);
String fujianType=mpart.getContentType();
String disposition="";
if(fujianType.indexOf("application/octet-stream")!=-1){
String[] a=mpart.getHeader("Content-Disposition");
if(a!=null){
for(int s=0;s<a.length;s++){
if(a[s].indexOf("attachment")!=-1){
disposition="attachment";
break;
}
}
}
}
disposition = mpart.getDisposition();
if((disposition != null) &&((disposition.equals(Part.ATTACHMENT)) ||(disposition.equals(Part.INLINE)))){
fileName = mpart.getFileName();
contentid=mpart.getHeader("Content-ID");
if(contentid!=null){//说明是图片
isPic=true;
}else{
isPic=false;
}
saveFile(fileName,mpart.getInputStream(),isPic,master);
}else if(mpart.isMimeType("multipart/*")){
saveAttachMent(mpart,master);
}else if(mpart.isMimeType("message/rfc822")){
fileName = mpart.getFileName();
contentid=mpart.getHeader("Content-ID");
if(contentid!=null){//说明是图片
isPic=true;
}else{
isPic=false;
}
if(fujianType.indexOf("text/html")!=-1||fujianType.indexOf("text/plain")!=-1){
continue;
}else{
saveFile(fileName,mpart.getInputStream(),isPic,master);
}
}
}
}else if(part.isMimeType("message/rfc822")){
saveAttachMent((Part)part.getContent(),master);
}else if(part.isMimeType("application/octet-stream")){
fileName=part.getFileName();
contentid=part.getHeader("Content-ID");
if(contentid!=null){//说明是图片
isPic=true;
}else{
isPic=false;
}
saveFile(fileName,part.getInputStream(),isPic,master);
}
}
//真正的保存附件到指定目录(保存附件)
private void saveFile(String fileName,InputStream in,boolean isPic,YxySendMailMasterBase master)throws Exception{
//图片保存
SimpleDateFormat df=new SimpleDateFormat("yyyyMMddHHmmss");
String nowFileName=df.format(new Date())+GetRandom.getRandomString(10);
//附件名编码解析
if(fileName.contains("=?")||fileName.contains("?B")){
fileName=MimeUtility.decodeText(fileName);
}else{
String newstr=fileName.replace("?", "");
newstr=new String(newstr.getBytes("iso-8859-1"));
if(!newstr.contains("?")){
fileName=new String(fileName.getBytes("iso-8859-1"));
}
}
//判断是图片还是附件
String picAndAttr="";
if(isPic){//解析图片
picAndAttr="pic";
//分割出图片后缀
String[] fileEx=fileName.split("\\.");
if(fileEx.length>=2){
fileName=nowFileName+"."+fileEx[1];
}else{
fileName=nowFileName;
}
}else if(!isPic){//解析附件
picAndAttr="attachment";
}else{
return;
}
String osName = System.getProperty("os.name");
String storedir =path()+"/mailtempfile/"+master.getUser_domain()+"/"+master.getUser_loginid()+"/"+picAndAttr;
String separator = "";
if (osName == null)
osName = "";
if (osName.toLowerCase().indexOf("win") != -1) {
separator = "\\";
if (storedir == null || storedir.equals(""))
storedir = "c:\\tmp";
}else {
separator = "/";
storedir = "/tmp";
}
File storefile = new File(storedir + separator);
if(!storefile.exists()){
storefile.mkdirs();
}
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
try {
String []houzhui=fileName.split("\\.");
if(houzhui.length>=2){
nowFileName=(nowFileName+"."+houzhui[1]);
}
if(!isPic){
attrName+=(nowFileName+"#####"+fileName)+",";
}
File isfileExite = new File(storefile+"/"+nowFileName);
if(!isfileExite.exists()){
bos = new BufferedOutputStream(new FileOutputStream(storefile+"/"+nowFileName));
bis = new BufferedInputStream(in);
int c;
while ((c = bis.read()) != -1) {
bos.write(c);
bos.flush();
}
}
} finally {
if(bos!=null){
bos.close();
bis.close();
}
}
//如果是图片则替换图片路径
if(isPic){
//cid的位置
int cidwhere=context.indexOf("cid");
if(cidwhere!=-1){
String str=context.substring(cidwhere,context.length());
int next=str.indexOf("/>");
String newStr="";
if(next==-1){
next=str.indexOf("'");
}
newStr=context.substring(cidwhere,(next-1)+cidwhere);
context=context.replace(newStr, "mailtempfile/"+master.getUser_domain()+"/"+master.getUser_loginid()+"/pic/"+nowFileName+"\"");
//result.set(0, context);
}else{
context=context+"</br><img src=/mailtempfile/"+master.getUser_domain()+"/"+master.getUser_loginid()+"/pic/"+nowFileName+"></img>";
}
}
}
//获得系统相对路径
public String path(){;
String pathew = this.getClass().getClassLoader().getResource("/").getPath();
pathew = pathew.substring(1, pathew.length());
pathew = pathew.replace("/WEB-INF/classes/","");
return pathew;
}
}