javamail to receive e-mail

2010-07-17  来源:本站原创  分类:Java  人气:280 

1.  import java.io.*;
   2. import java.text.*;
   3. import java.util.*;
   4. import javax.mail.*;
   5. import javax.mail.internet.*;
   6.
   7. /**
   8.  *   Have a message object needs to create a ReciveMail
   9.  */
  10. public class ReciveOneMail {
  11.     private MimeMessage mimeMessage = null;
  12.     private String saveAttachPath = ""; //  Store directory after downloading attachments
  13.     private StringBuffer bodytext = new StringBuffer();//  Storing message content
  14.     private String dateformat = "yy-MM-dd HH:mm"; //  The default display format for a few days ago
  15.
  16.     public ReciveOneMail(MimeMessage mimeMessage) {
  17.         this.mimeMessage = mimeMessage;
  18.     }
  19.
  20.     public void setMimeMessage(MimeMessage mimeMessage) {
  21.         this.mimeMessage = mimeMessage;
  22.     }
  23.
  24.     /**
  25.      *   Access to the sender's address and name
  26.      */
  27.     public String getFrom() throws Exception {
  28.         InternetAddress address[] = (InternetAddress[]) mimeMessage.getFrom();
  29.         String from = address[0].getAddress();
  30.         if (from == null)
  31.             from = "";
  32.         String personal = address[0].getPersonal();
  33.         if (personal == null)
  34.             personal = "";
  35.         String fromaddr = personal + "<" + from + ">";
  36.         return fromaddr;
  37.     }
  38.
  39.     /**
  40.      *   Get the message, Cc  , And Bcc address and name, according to the different parameters passed   "to"----  Recipient "cc" --- CC's address   "bcc"---  Anyone to address density
  41.      */
  42.     public String getMailAddress(String type) throws Exception {
  43.         String mailaddr = "";
  44.         String addtype = type.toUpperCase();
  45.         InternetAddress[] address = null;
  46.         if (addtype.equals("TO") || addtype.equals("CC")|| addtype.equals("BCC")) {
  47.             if (addtype.equals("TO")) {
  48.                 address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.TO);
  49.             } else if (addtype.equals("CC")) {
  50.                 address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.CC);
  51.             } else {
  52.                 address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.BCC);
  53.             }
  54.             if (address != null) {
  55.                 for (int i = 0; i < address.length; i++) {
  56.                     String email = address[i].getAddress();
  57.                     if (email == null)
  58.                         email = "";
  59.                     else {
  60.                         email = MimeUtility.decodeText(email);
  61.                     }
  62.                     String personal = address[i].getPersonal();
  63.                     if (personal == null)
  64.                         personal = "";
  65.                     else {
  66.                         personal = MimeUtility.decodeText(personal);
  67.                     }
  68.                     String compositeto = personal + "<" + email + ">";
  69.                     mailaddr += "," + compositeto;
  70.                 }
  71.                 mailaddr = mailaddr.substring(1);
  72.             }
  73.         } else {
  74.             throw new Exception("Error emailaddr type!");
  75.         }
  76.         return mailaddr;
  77.     }
  78.
  79.     /**
  80.      *   Access to the message subject
  81.      */
  82.     public String getSubject() throws MessagingException {
  83.         String subject = "";
  84.         try {
  85.             subject = MimeUtility.decodeText(mimeMessage.getSubject());
  86.             if (subject == null)
  87.                 subject = "";
  88.         } catch (Exception exce) {}
  89.         return subject;
  90.     }
  91.
  92.     /**
  93.      *   Date received mail
  94.      */
  95.     public String getSentDate() throws Exception {
  96.         Date sentdate = mimeMessage.getSentDate();
  97.         SimpleDateFormat format = new SimpleDateFormat(dateformat);
  98.         return format.format(sentdate);
  99.     }
 100.
 101.     /**
 102.      *   Access to the contents of the message body
 103.      */
 104.     public String getBodyText() {
 105.         return bodytext.toString();
 106.     }
 107.
 108.     /**
 109.      *   Parsing the message, to get the message content stored in a  StringBuffer  Object, parsing the message     MimeType type is mainly based on the implementation of different actions of different  ,  Analysis step by step
 110.      */
 111.     public void getMailContent(Part part) throws Exception {
 112.         String contenttype = part.getContentType();
 113.         int nameindex = contenttype.indexOf("name");
 114.         boolean conname = false;
 115.         if (nameindex != -1)
 116.             conname = true;
 117.         System.out.println("CONTENTTYPE: " + contenttype);
 118.         if (part.isMimeType("text/plain") && !conname) {
 119.             bodytext.append((String) part.getContent());
 120.         } else if (part.isMimeType("text/html") && !conname) {
 121.             bodytext.append((String) part.getContent());
 122.         } else if (part.isMimeType("multipart/*")) {
 123.             Multipart multipart = (Multipart) part.getContent();
 124.             int counts = multipart.getCount();
 125.             for (int i = 0; i < counts; i++) {
 126.                 getMailContent(multipart.getBodyPart(i));
 127.             }
 128.         } else if (part.isMimeType("message/rfc822")) {
 129.             getMailContent((Part) part.getContent());
 130.         } else {}
 131.     }
 132.
 133.     /**
 134.      *   Determine whether the message receipt, return receipt if needed  "true",  Otherwise  "false"
 135.      */
 136.     public boolean getReplySign() throws MessagingException {
 137.         boolean replysign = false;
 138.         String needreply[] = mimeMessage
 139.                 .getHeader("Disposition-Notification-To");
 140.         if (needreply != null) {
 141.             replysign = true;
 142.         }
 143.         return replysign;
 144.     }
 145.
 146.     /**
 147.      *   Get this message  Message-ID
 148.      */
 149.     public String getMessageId() throws MessagingException {
 150.         return mimeMessage.getMessageID();
 151.     }
 152.
 153.     /**
 154.      * [  To determine whether this message has been read, if not read Back to return   false,  Instead Back  true]
 155.      */
 156.     public boolean isNew() throws MessagingException {
 157.         boolean isnew = false;
 158.         Flags flags = ((Message) mimeMessage).getFlags();
 159.         Flags.Flag[] flag = flags.getSystemFlags();
 160.         System.out.println("flags's length: " + flag.length);
 161.         for (int i = 0; i < flag.length; i++) {
 162.             if (flag[i] == Flags.Flag.SEEN) {
 163.                 isnew = true;
 164.                 System.out.println("seen Message.......");
 165.                 break;
 166.             }
 167.         }
 168.         return isnew;
 169.     }
 170.
 171.     /**
 172.      *   Determine whether the message contains an attachment
 173.      */
 174.     public boolean isContainAttach(Part part) throws Exception {
 175.         boolean attachflag = false;
 176.         String contentType = part.getContentType();
 177.         if (part.isMimeType("multipart/*")) {
 178.             Multipart mp = (Multipart) part.getContent();
 179.             for (int i = 0; i < mp.getCount(); i++) {
 180.                 BodyPart mpart = mp.getBodyPart(i);
 181.                 String disposition = mpart.getDisposition();
 182.                 if ((disposition != null)
 183.                         && ((disposition.equals(Part.ATTACHMENT)) || (disposition
 184.                                 .equals(Part.INLINE))))
 185.                     attachflag = true;
 186.                 else if (mpart.isMimeType("multipart/*")) {
 187.                     attachflag = isContainAttach((Part) mpart);
 188.                 } else {
 189.                     String contype = mpart.getContentType();
 190.                     if (contype.toLowerCase().indexOf("application") != -1)
 191.                         attachflag = true;
 192.                     if (contype.toLowerCase().indexOf("name") != -1)
 193.                         attachflag = true;
 194.                 }
 195.             }
 196.         } else if (part.isMimeType("message/rfc822")) {
 197.             attachflag = isContainAttach((Part) part.getContent());
 198.         }
 199.         return attachflag;
 200.     }
 201.
 202.     /**
 203.      * [  Save Attachments  ]
 204.      */
 205.     public void saveAttachMent(Part part) throws Exception {
 206.         String fileName = "";
 207.         if (part.isMimeType("multipart/*")) {
 208.             Multipart mp = (Multipart) part.getContent();
 209.             for (int i = 0; i < mp.getCount(); i++) {
 210.                 BodyPart mpart = mp.getBodyPart(i);
 211.                 String disposition = mpart.getDisposition();
 212.                 if ((disposition != null)
 213.                         && ((disposition.equals(Part.ATTACHMENT)) || (disposition
 214.                                 .equals(Part.INLINE)))) {
 215.                     fileName = mpart.getFileName();
 216.                     if (fileName.toLowerCase().indexOf("gb2312") != -1) {
 217.                         fileName = MimeUtility.decodeText(fileName);
 218.                     }
 219.                     saveFile(fileName, mpart.getInputStream());
 220.                 } else if (mpart.isMimeType("multipart/*")) {
 221.                     saveAttachMent(mpart);
 222.                 } else {
 223.                     fileName = mpart.getFileName();
 224.                     if ((fileName != null)
 225.                             && (fileName.toLowerCase().indexOf("GB2312") != -1)) {
 226.                         fileName = MimeUtility.decodeText(fileName);
 227.                         saveFile(fileName, mpart.getInputStream());
 228.                     }
 229.                 }
 230.             }
 231.         } else if (part.isMimeType("message/rfc822")) {
 232.             saveAttachMent((Part) part.getContent());
 233.         }
 234.     }
 235.
 236.     /**
 237.      * [  Annex storage path set  ]
 238.      */
 239.
 240.     public void setAttachPath(String attachpath) {
 241.         this.saveAttachPath = attachpath;
 242.     }
 243.
 244.     /**
 245.      * [  Set the date display format  ]
 246.      */
 247.     public void setDateFormat(String format) throws Exception {
 248.         this.dateformat = format;
 249.     }
 250.
 251.     /**
 252.      * [  Access to attachments stored path  ]
 253.      */
 254.     public String getAttachPath() {
 255.         return saveAttachPath;
 256.     }
 257.
 258.     /**
 259.      * [  True to the specified directory to save the attachment  ]
 260.      */
 261.     private void saveFile(String fileName, InputStream in) throws Exception {
 262.         String osName = System.getProperty("os.name");
 263.         String storedir = getAttachPath();
 264.         String separator = "";
 265.         if (osName == null)
 266.             osName = "";
 267.         if (osName.toLowerCase().indexOf("win") != -1) {
 268.             separator = "\\";
 269.             if (storedir == null || storedir.equals(""))
 270.                 storedir = "c:\\tmp";
 271.         } else {
 272.             separator = "/";
 273.             storedir = "/tmp";
 274.         }
 275.         File storefile = new File(storedir + separator + fileName);
 276.         System.out.println("storefile's path: " + storefile.toString());
 277.         // for(int i=0;storefile.exists();i++){
 278.         // storefile = new File(storedir+separator+fileName+i);
 279.         // }
 280.         BufferedOutputStream bos = null;
 281.         BufferedInputStream bis = null;
 282.         try {
 283.             bos = new BufferedOutputStream(new FileOutputStream(storefile));
 284.             bis = new BufferedInputStream(in);
 285.             int c;
 286.             while ((c = bis.read()) != -1) {
 287.                 bos.write(c);
 288.                 bos.flush();
 289.             }
 290.         } catch (Exception exception) {
 291.             exception.printStackTrace();
 292.             throw new Exception("  Failed to save the file  !");
 293.         } finally {
 294.             bos.close();
 295.             bis.close();
 296.         }
 297.     }
 298.
 299.     /**
 300.      * PraseMimeMessage  Class test
 301.      */
 302.     public static void main(String args[]) throws Exception {
 303.         Properties props = System.getProperties();
 304.         props.put("mail.smtp.host", "smtp.163.com");
 305.         props.put("mail.smtp.auth", "true");
 306.         Session session = Session.getDefaultInstance(props, null);
 307.         URLName urln = new URLName("pop3", "pop3.163.com", 110, null,
 308.                 "xiangzhengyan", "pass");
 309.         Store store = session.getStore(urln);
 310.         store.connect();
 311.         Folder folder = store.getFolder("INBOX");
 312.         folder.open(Folder.READ_ONLY);
 313.         Message message[] = folder.getMessages();
 314.         System.out.println("Messages's length: " + message.length);
 315.         ReciveOneMail pmm = null;
 316.         for (int i = 0; i < message.length; i++) {
 317.             System.out.println("======================");
 318.             pmm = new ReciveOneMail((MimeMessage) message[i]);
 319.             System.out.println("Message " + i + " subject: " + pmm.getSubject());
 320.             System.out.println("Message " + i + " sentdate: "+ pmm.getSentDate());
 321.             System.out.println("Message " + i + " replysign: "+ pmm.getReplySign());
 322.             System.out.println("Message " + i + " hasRead: " + pmm.isNew());
 323.             System.out.println("Message " + i + "  containAttachment: "+ pmm.isContainAttach((Part) message[i]));
 324.             System.out.println("Message " + i + " form: " + pmm.getFrom());
 325.             System.out.println("Message " + i + " to: "+ pmm.getMailAddress("to"));
 326.             System.out.println("Message " + i + " cc: "+ pmm.getMailAddress("cc"));
 327.             System.out.println("Message " + i + " bcc: "+ pmm.getMailAddress("bcc"));
 328.             pmm.setDateFormat("yy   MM month of  dd  Date  HH:mm");
 329.             System.out.println("Message " + i + " sentdate: "+ pmm.getSentDate());
 330.             System.out.println("Message " + i + " Message-ID: "+ pmm.getMessageId());
 331.             //   Access to message content  ===============
 332.             pmm.getMailContent((Part) message[i]);
 333.             System.out.println("Message " + i + " bodycontent: \r\n"
 334.                     + pmm.getBodyText());
 335.             pmm.setAttachPath("c:\\");
 336.             pmm.saveAttachMent((Part) message[i]);
 337.         }
 338.     }
 339. }  
相关文章
  • javamail to receive e-mail 2010-07-17

    1. import java.io.*; 2. import java.text.*; 3. import java.util.*; 4. import javax.mail.*; 5. import javax.mail.internet.*; 6. 7. /** 8. * Have a message object needs to create a ReciveMail 9. */ 10. public class ReciveOneMail { 11. private MimeMessa

  • JavaMail simple to use and instructions 2010-03-29

    SMTP: Simple Mail Transfer Protocol (Simple Mail Transfer Protocol, SMTP) defined by RFC821, which defines mechanisms for sending messages in JavaMail environment, the procedure will be based on JavaMail and Internet service providers ISP (internet S

  • JavaMail Application 2010-03-29

    Transfer from: http://www.blogjava.net/BlueSUN/archive/2007/04/18/111750.html I do have a little software development for years, look back and think, has gone through a lot of ups and downs, in order to solve complex problems than pleasure. Also work

  • javamail Frequently Asked Questions 2008-10-29

    General Questions Asked. What is the JavaMail API? Answer: JavaMail API is a set of abstract API, it can be used to build e-mail system. API provides a platform-independent and protocol-independent framework for building Java-based technology, e-mail

  • javamail receiving (pop3) e-mail 2010-11-07

    Theme: javamail receiving (pop3) e-mail Note: Attached is a complete example, contains two classes, which class is set to log mail MailReceiverInfo parameters, such as parameter to MailReceiver class, MailReceiver mail contains a variety of methods o

  • Chat-based mail server code sample test ------ 2010-12-22

    Now a lot of the mail service provider, and the speed of the mailbox is also very good, but also between each other the information, chat-based mail server for information, should also be good. Write a simple version of the client-side tool under tes

  • In the java EE 5.0 developed under the java mail problems encountered and solutions 2010-03-22

    Make a java EE recent small-scale projects, using a java EE 5.0, the project there is a module is to automatically send a message to the customer, so it is natural to develop using java mail. But the question on the hit, the code is not running the c

  • Using JavaMail in JSP 2010-07-14

    In this article you can learn some of the points JavaMail API and how to use it in JSP. This also includes the use of JavaMail in JSP examples. JavaMail JSP application is very strong in the API. Jsp you want to create a mail collection tools? Is des

  • E-mail send and receive a comprehensive analysis of the failure 2010-08-08

    Internet e-mail is one of the most important applications, it provides a very convenient and fast means of communication. However, many users have had the experience of e-mail failures. The following E-mail the author by the failure of transceivers f

  • java development tools Mail 2011-05-02

    Properties file: # All major mail server address book, receive key representatives at the end of the receiving server address , send Key representatives at the end of the sending server address # NetEase 126 mailbox host.126.receive=pop3.126.com host

  • Php in the mail from the local through msmtp 2011-06-21

    See http://www.absolutelytech.com/2010/07/18/howto-send-emailsusing-mail-function-from-localhost-in-php-through-msmtp-using-gmail-account-on-linux/ of steps: Step by step instructions: First of all, follow this tutorial: Box msmtp on your Linux insta

  • Linux: mail the mail and check 2011-08-02

    System receives the message will be saved in "/ var / spool / mail / [linux user name]" file. In linux, type mail, the conduct of the Inbox, and shows the twenty mailing list. At this point the command prompt as "&" unread messages

  • 基于JavaMail的常用类详细介绍 2015-04-02

    以下是对JavaMail的常用类进行了详细分析的介绍,需要的朋友可以过来参考下 应用服务器 (1) javax.mail.Properties类 JavaMail需要Properties来创建一个session对象.它将寻找字符串"mail.smtp.host",属性值就是发送邮件的主机. 用法: Properties props = new Properties (); props.put("mail.smtp.host", "smtp.163.com&

  • JSP中使用JavaMail 2015-04-25

    你希望在jsp中建立一个邮件发送收取工具吗?下面将介绍的就是在jsp中建立一个邮件发送收取工具.在这篇文章中你可以了解到JavaMail API的一些要点以及如何在JSP中使用它.本文中还包括了在JSP中使用JavaMail的实例.JavaMail是JSP应用软件中相当强大的API. 阅读这篇文章需要对JSP.JavaBeans和JavaMail有一定的初步了解.当然,有关于JavaMail的知识你可以通过阅读这篇文章来获得.如果你对于以上三项一无所知,但你所使用的服务器支持JSP和JavaMa

  • JavaMail的使用 2013-07-22

    Javamail是用来发送邮件的一个常用框架,我以前用过这个框架写过一个发送邮件的demo,以下内容是我以前整理的. 1javamail的使用 我是使用mavne的,所以引用了如下的依赖,如果不引入第二个依赖的话会报javamail的一个log类找不到 <dependency> <groupId>javax.mail</groupId> <artifactId>javax.mail-api</artifactId> <version>

  • domino_ Encyclopedia FAQ Center 2010-09-29

    1, Q: DOMCFG login Login button appears at the bottom of the A: to add the final surface <div> 2, Q: newly installed server, copy the DOMINO directory is still build another server to launch the initial directory server A: To modify the following re

  • General idea of ​​rapid detection method of fault messages 2011-03-26

    A wide range of mail server software, but most can not do without SMTP (Simple Mail Transfer Protocol), this article from the SMTP protocol to start explaining how to detect a general e-mail failure. So here you do not have to consider or use the EXC

  • Solaris for process management 2010-04-09

    1. Lists the process ps # Ps-f / / show the details of the current user process UID PID PPID C STIME TTY TIME CMD root 4737 4724 0 09:39:39 pts / 2 0:00 bash root 4755 4737 0 10:10:05 pts / 2 0:00 ps-f # Ps-Af / / lists all processes and detailed sys

  • Internet Marketing Data Interpretation (2) - Things are not as you see 2010-04-25

    Last (Please click here to see "things are not as you see - Internet marketing data interpretation (1 ) ") out of 10 questions that ask whether the conclusion we must correct a lot of friends also join in to answer questions. Basically, the 10 q

  • Evolution under Ubuntu and other e-mail configuration 2010-05-22

    I use our company's enterprise-class hosted email for example, hosted by: NetEase 1, first of all you have to set the mailbox access to POP, SMTP address and port number of the corresponding Second, open Evolution preferences, add the mail account Th