一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服務(wù)器之家 - 編程語言 - JAVA教程 - java Mail郵件接收工具類

java Mail郵件接收工具類

2019-12-10 13:43junjie JAVA教程

這篇文章主要介紹了java Mail郵件接收工具類,本文直接給出類實(shí)現(xiàn)代碼和使用示例,需要的朋友可以參考下

下面是一個郵件接收的工具類,有點(diǎn)長!!!

?
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
342
343
344
345
346
347
348
349
350
public class ReciveMail {
 private MimeMessage msg = null;
  private String saveAttchPath = "";
  private StringBuffer bodytext = new StringBuffer();
  private String dateformate = "yy-MM-dd HH:mm";
  
  public ReciveMail(MimeMessage msg){
    this.msg = msg;
    }
  public void setMsg(MimeMessage msg) {
    this.msg = msg;
  }
  
  /**
   * 獲取發(fā)送郵件者信息
   * @return
   * @throws MessagingException
   */
  public String getFrom() throws MessagingException{
    InternetAddress[] address = (InternetAddress[]) msg.getFrom();
    String from = address[0].getAddress();
    if(from == null){
      from = "";
    }
    String personal = address[0].getPersonal();
    if(personal == null){
      personal = "";
    }
    String fromaddr = personal +"<"+from+">";
    return fromaddr;
  }
  
  /**
   * 獲取郵件收件人,抄送,密送的地址和信息。根據(jù)所傳遞的參數(shù)不同 "to"-->收件人,"cc"-->抄送人地址,"bcc"-->密送地址
   * @param type
   * @return
   * @throws MessagingException
   * @throws UnsupportedEncodingException
   */
  public String getMailAddress(String type) throws MessagingException, UnsupportedEncodingException{
    String mailaddr = "";
    String addrType = type.toUpperCase();
    InternetAddress[] address = null;
    
    if(addrType.equals("TO")||addrType.equals("CC")||addrType.equals("BCC")){
      if(addrType.equals("TO")){
        address = (InternetAddress[]) msg.getRecipients(Message.RecipientType.TO);
      }
      if(addrType.equals("CC")){
        address = (InternetAddress[]) msg.getRecipients(Message.RecipientType.CC);
      }
      if(addrType.equals("BCC")){
        address = (InternetAddress[]) msg.getRecipients(Message.RecipientType.BCC);
      }   
      if(address != null){
        for(int i=0;i<address.length;i++){
          String mail = address[i].getAddress();
          if(mail == null){
            mail = "";
          }else{
            mail = MimeUtility.decodeText(mail);
          }
          String personal = address[i].getPersonal();
          if(personal == null){
            personal = "";
          }else{
            personal = MimeUtility.decodeText(personal);
          }
          String compositeto = personal +"<"+mail+">";
          mailaddr += ","+compositeto;
        }
        mailaddr = mailaddr.substring(1);
      }
    }else{
      throw new RuntimeException("Error email Type!");
    }
    return mailaddr;
  }
  
  /**
   * 獲取郵件主題
   * @return
   * @throws UnsupportedEncodingException
   * @throws MessagingException
   */
  public String getSubject() throws UnsupportedEncodingException, MessagingException{
    String subject = "";
    subject = MimeUtility.decodeText(msg.getSubject());
    if(subject == null){
      subject = "";
    }
    return subject;
  }
  
  /**
   * 獲取郵件發(fā)送日期
   * @return
   * @throws MessagingException
   */
  public String getSendDate() throws MessagingException{
    Date sendDate = msg.getSentDate();
    SimpleDateFormat smd = new SimpleDateFormat(dateformate);
    return smd.format(sendDate);
  }
  
  /**
   * 獲取郵件正文內(nèi)容
   * @return
   */
  public String getBodyText(){
    return bodytext.toString();
  }
  
  /**
   * 解析郵件,將得到的郵件內(nèi)容保存到一個stringBuffer對象中,
   * 解析郵件 主要根據(jù)MimeType的不同執(zhí)行不同的操作,一步一步的解析
   * @param part
   * @throws MessagingException
   * @throws IOException
   */
  public void getMailContent(Part part) throws MessagingException, IOException{
    
    String contentType = part.getContentType();
    int nameindex = contentType.indexOf("name");
    boolean conname = false;
    if(nameindex != -1){
      conname = true;
    }
    System.out.println("CONTENTTYPE:"+contentType);
    if(part.isMimeType("text/plain")&&!conname){
      bodytext.append((String)part.getContent());
    }else if(part.isMimeType("text/html")&&!conname){
      bodytext.append((String)part.getContent());
    }else if(part.isMimeType("multipart/*")){
      Multipart multipart = (Multipart) part.getContent();
      int count = multipart.getCount();
      for(int i=0;i<count;i++){
        getMailContent(multipart.getBodyPart(i));
      }
    }else if(part.isMimeType("message/rfc822")){
      getMailContent((Part) part.getContent());
    }
    
  }
  
  /**
   * 判斷郵件是否需要回執(zhí),如需回執(zhí)返回true,否則返回false
   * @return
   * @throws MessagingException
   */
  public boolean getReplySign() throws MessagingException{
    boolean replySign = false;
    String needreply[] = msg.getHeader("Disposition-Notification-TO");
    if(needreply != null){
      replySign = true;
    }
    return replySign;
  }
  
  /**
   * 獲取此郵件的message-id
   * @return
   * @throws MessagingException
   */
  public String getMessageId() throws MessagingException{
    return msg.getMessageID();
  }
  
  /**
   * 判斷此郵件是否已讀,如果未讀則返回false,已讀返回true
   * @return
   * @throws MessagingException
   */
  public boolean isNew() throws MessagingException{
    boolean isnew = false;
    Flags flags = ((Message)msg).getFlags();
    Flags.Flag[] flag = flags.getSystemFlags();
    System.out.println("flags's length:"+flag.length);
    for(int i=0;i<flag.length;i++){
      if(flag[i]==Flags.Flag.SEEN){
        isnew = true;
        System.out.println("seen message .......");
        break;
      }
    }
    return isnew;
  }
  
  /**
   * 判斷是是否包含附件
   * @param part
   * @return
   * @throws MessagingException
   * @throws IOException
   */
  public boolean isContainAttch(Part part) throws MessagingException, IOException{
    boolean flag = false;
    
    //String contentType = part.getContentType();
    if(part.isMimeType("multipart/*")){
      Multipart multipart = (Multipart) part.getContent();
      int count = multipart.getCount();
      for(int i=0;i<count;i++){
        BodyPart bodypart = multipart.getBodyPart(i);
        String dispostion = bodypart.getDisposition();
        if((dispostion != null)&&(dispostion.equals(Part.ATTACHMENT)||dispostion.equals(Part.INLINE))){
          flag = true;
        }else if(bodypart.isMimeType("multipart/*")){
          flag = isContainAttch(bodypart);
        }else{
          String conType = bodypart.getContentType();
          if(conType.toLowerCase().indexOf("appliaction")!=-1){
            flag = true;
          }
          if(conType.toLowerCase().indexOf("name")!=-1){
            flag = true;
          }
        }
      }
    }else if(part.isMimeType("message/rfc822")){
      flag = isContainAttch((Part) part.getContent());
    }
    
    return flag;
  }
  
  /**
   * 保存附件
   * @param part
   * @throws MessagingException
   * @throws IOException
   */
  public void saveAttchMent(Part part) throws MessagingException, IOException{
    String filename = "";
    if(part.isMimeType("multipart/*")){
      Multipart mp = (Multipart) part.getContent();
      for(int i=0;i<mp.getCount();i++){
        BodyPart mpart = mp.getBodyPart(i);
        String dispostion = mpart.getDisposition();
        if((dispostion != null)&&(dispostion.equals(Part.ATTACHMENT)||dispostion.equals(Part.INLINE))){
          filename = mpart.getFileName();
          if(filename.toLowerCase().indexOf("gb2312")!=-1){
            filename = MimeUtility.decodeText(filename);
          }
          saveFile(filename,mpart.getInputStream());
        }else if(mpart.isMimeType("multipart/*")){
          saveAttchMent(mpart);
        }else{
          filename = mpart.getFileName();
          if(filename != null&&(filename.toLowerCase().indexOf("gb2312")!=-1)){
            filename = MimeUtility.decodeText(filename);
          }
          saveFile(filename,mpart.getInputStream());
        }
      }
      
    }else if(part.isMimeType("message/rfc822")){
      saveAttchMent((Part) part.getContent());
    }
  }
  /**
   * 獲得保存附件的地址
   * @return
   */
  public String getSaveAttchPath() {
    return saveAttchPath;
  }
  /**
   * 設(shè)置保存附件地址
   * @param saveAttchPath
   */
  public void setSaveAttchPath(String saveAttchPath) {
    this.saveAttchPath = saveAttchPath;
  }
  /**
   * 設(shè)置日期格式
   * @param dateformate
   */
  public void setDateformate(String dateformate) {
    this.dateformate = dateformate;
  }
  /**
   * 保存文件內(nèi)容
   * @param filename
   * @param inputStream
   * @throws IOException
   */
  private void saveFile(String filename, InputStream inputStream) throws IOException {
    String osname = System.getProperty("os.name");
    String storedir = getSaveAttchPath();
    String sepatror = "";
    if(osname == null){
      osname = "";
    }
    
    if(osname.toLowerCase().indexOf("win")!=-1){
      sepatror = "//";
      if(storedir==null||"".equals(storedir)){
        storedir = "d://temp";
      }
    }else{
      sepatror = "/";
      storedir = "/temp";
    }
    
    File storefile = new File(storedir+sepatror+filename);
    System.out.println("storefile's path:"+storefile.toString());
    
    BufferedOutputStream bos = null;
    BufferedInputStream bis = null;
    
    try {
      bos = new BufferedOutputStream(new FileOutputStream(storefile));
      bis = new BufferedInputStream(inputStream);
      int c;
      while((c= bis.read())!=-1){
        bos.write(c);
        bos.flush();
      }
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }finally{
      bos.close();
      bis.close();
    }
    
  }
  
  public void recive(Part part,int i) throws MessagingException, IOException{
    System.out.println("------------------START-----------------------");
    System.out.println("Message"+i+" subject:" + getSubject());
    System.out.println("Message"+i+" from:" + getFrom());
    System.out.println("Message"+i+" isNew:" + isNew());
    boolean flag = isContainAttch(part);
    System.out.println("Message"+i+" isContainAttch:" +flag);
    System.out.println("Message"+i+" replySign:" + getReplySign());
    getMailContent(part);
    System.out.println("Message"+i+" content:" + getBodyText());
    setSaveAttchPath("c://temp//"+i);
    if(flag){
      saveAttchMent(part);
    }
    System.out.println("------------------END-----------------------");
  }
 
}

郵件接收與工具類的使用,有好幾種郵件接收的寫法!:

看了很多網(wǎng)上其他代碼,pop3Server的值是pop.mail.163.com,但是試了試不成功,還有 user的值既可以是帶有 [email protected]也可以是username。

如果收件郵箱是163郵箱,必須先登陸163郵箱中設(shè)置,開啟pop3服務(wù)。至于別的郵箱暫不知道。

?
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
public static void main(String[] args) throws Exception {
    // 連接pop3服務(wù)器的主機(jī)名、協(xié)議、用戶名、密碼
    String pop3Server = "pop.163.com";
    String protocol = "pop3";
    String user = "username";
    String pwd = "password";
     
    // 創(chuàng)建一個有具體連接信息的Properties對象
    Properties props = new Properties();
    props.setProperty("mail.store.protocol", protocol);
    props.setProperty("mail.pop3.host", pop3Server);
     
    // 使用Properties對象獲得Session對象
    Session session = Session.getInstance(props);
    session.setDebug(true);
     
    // 利用Session對象獲得Store對象,并連接pop3服務(wù)器
    Store store = session.getStore();
    store.connect(pop3Server, user, pwd);
     
    // 獲得郵箱內(nèi)的郵件夾Folder對象,以"只讀"打開
    Folder folder = store.getFolder("inbox");
    folder.open(Folder.READ_ONLY);
     
    // 獲得郵件夾Folder內(nèi)的所有郵件Message對象
    Message [] messages = folder.getMessages(); 
    ReciveMail rm = null;
    for(int i=0;i< messages.size() ;i++){
      rm = new ReciveMail((MimeMessage) messages[i]);
      rm.recive(messages[i],i);;
    }
     folder.close(false);
    store.close();
}

 

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 免费黄色片网站 | 1024免费永久福利视频 | 4hu影院永久在线播放 | 青草热视频 | 亚洲第一网站免费视频 | 免费视频 | 国产精品午夜剧场 | 91社区在线观看精品 | 2021国产精品露脸在线 | 高清欧美videossexo免费 | 国模丰满美女冰漪34d | 日本在线一区二区 | 色人阁图片 | 亚洲国产成人久久99精品 | 激情五色月 | 免费高清视频免费观看 | 精油按摩日本 | 毛毛片在线 | 国产成人性色视频 | 亚洲va欧美va国产va天堂影 | 久久中文字幕亚洲 | 免费精品一区二区三区在线观看 | 国产自在自线午夜精品之la | 手机av | 91夜夜人人揉人人捏人人添 | 国产精品精品 | 成人性生交小说免费看 | 日本不卡在线一区二区三区视频 | 青柠网在线观看视频 | 亚洲欧美一级夜夜爽w | 美女裆部| 国产成人综合手机在线播放 | 欧美色综合高清免费 | 91精品国产99久久 | 国产香蕉国产精品偷在线观看 | 黑人biglackon10十 | 日本一区二区在线不卡 | 久久视频在线视频观看精品15 | 2048论坛永久入口 原创合集 | 欧美夫妇野外交换hd高清版 | a级片在线播放 |