首页   资讯   精华   论坛   问答   博客   专栏   群组   更多  

招聘搜索

您还未登录 !     登录     注册  

XZY的学习笔记

xiangzhengyan

javamail接收邮件(较全)          

博客分类: Java EE

CC++C#OS 

java 代码

  1. import java.io.*;   

  2. import java.text.*;   

  3. import java.util.*;   

  4. import javax.mail.*;   

  5. import javax.mail.internet.*;   

  6. /**

  7.  * 有一封邮件就需要建立一个ReciveMail对象

  8.  */

  9. public class ReciveOneMail {   

  10.     private MimeMessage mimeMessage = null;   

  11.     private String saveAttachPath = ""//附件下载后的存放目录

  12.     private StringBuffer bodytext = new StringBuffer();//存放邮件内容

  13.     private String dateformat = "yy-MM-dd HH:mm"//默认的日前显示格式

  14.     public ReciveOneMail(MimeMessage mimeMessage) {   

  15.         this.mimeMessage = mimeMessage;   

  16.     }   

  17.     public void setMimeMessage(MimeMessage mimeMessage) {   

  18.         this.mimeMessage = mimeMessage;   

  19.     }   

  20.     /**

  21.      * 获得发件人的地址和姓名

  22.      */

  23.     public String getFrom() throws Exception {   

  24.         InternetAddress address[] = (InternetAddress[]) mimeMessage.getFrom();   

  25.         String from = address[0].getAddress();   

  26.         if (from == null)   

  27.             from = "";   

  28.         String personal = address[0].getPersonal();   

  29.         if (personal == null)   

  30.             personal = "";   

  31.         String fromaddr = personal + "<"< span=""> + from + ">";   

  32.         return fromaddr;   

  33.     }   

  34.     /**

  35.      * 获得邮件的收件人,抄送,和密送的地址和姓名,根据所传递的参数的不同 "to"----收件人 "cc"---抄送人地址 "bcc"---密送人地址

  36.      */

  37.     public String getMailAddress(String type) throws Exception {   

  38.         String mailaddr = "";   

  39.         String addtype = type.toUpperCase();   

  40.         InternetAddress[] address = null;   

  41.         if (addtype.equals("TO") || addtype.equals("CC")|| addtype.equals("BCC")) {   

  42.             if (addtype.equals("TO")) {   

  43.                 address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.TO);   

  44.             } else if (addtype.equals("CC")) {   

  45.                 address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.CC);   

  46.             } else {   

  47.                 address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.BCC);   

  48.             }   

  49.             if (address != null) {   

  50.                 for (int i = 0; i < address.length; i++) {   

  51.                     String email = address[i].getAddress();   

  52.                     if (email == null)   

  53.                         email = "";   

  54.                     else {   

  55.                         email = MimeUtility.decodeText(email);   

  56.                     }   

  57.                     String personal = address[i].getPersonal();   

  58.                     if (personal == null)   

  59.                         personal = "";   

  60.                     else {   

  61.                         personal = MimeUtility.decodeText(personal);   

  62.                     }   

  63.                     String compositeto = personal + "<"< span=""> + email + ">";   

  64.                     mailaddr += "," + compositeto;   

  65.                 }   

  66.                 mailaddr = mailaddr.substring(1);   

  67.             }   

  68.         } else {   

  69.             throw new Exception("Error emailaddr type!");   

  70.         }   

  71.         return mailaddr;   

  72.     }   

  73.     /**

  74.      * 获得邮件主题

  75.      */

  76.     public String getSubject() throws MessagingException {   

  77.         String subject = "";   

  78.         try {   

  79.             subject = MimeUtility.decodeText(mimeMessage.getSubject());   

  80.             if (subject == null)   

  81.                 subject = "";   

  82.         } catch (Exception exce) {}   

  83.         return subject;   

  84.     }   

  85.     /**

  86.      * 获得邮件发送日期

  87.      */

  88.     public String getSentDate() throws Exception {   

  89.         Date sentdate = mimeMessage.getSentDate();   

  90.         SimpleDateFormat format = new SimpleDateFormat(dateformat);   

  91.         return format.format(sentdate);   

  92.     }   

  93.     /**

  94.      * 获得邮件正文内容

  95.      */

  96.     public String getBodyText() {   

  97.         return bodytext.toString();   

  98.     }   

  99.     /**

  100.      * 解析邮件,把得到的邮件内容保存到一个StringBuffer对象中,解析邮件 主要是根据MimeType类型的不同执行不同的操作,一步一步的解析

  101.      */

  102.     public void getMailContent(Part part) throws Exception {   

  103.         String contenttype = part.getContentType();   

  104.         int nameindex = contenttype.indexOf("name");   

  105.         boolean conname = false;   

  106.         if (nameindex != -1)   

  107.             conname = true;   

  108.         System.out.println("CONTENTTYPE: " + contenttype);   

  109.         if (part.isMimeType("text/plain") && !conname) {   

  110.             bodytext.append((String) part.getContent());   

  111.         } else if (part.isMimeType("text/html") && !conname) {   

  112.             bodytext.append((String) part.getContent());   

  113.         } else if (part.isMimeType("multipart/*")) {   

  114.             Multipart multipart = (Multipart) part.getContent();   

  115.             int counts = multipart.getCount();   

  116.             for (int i = 0; i < counts; i++) {   

  117.                 getMailContent(multipart.getBodyPart(i));   

  118.             }   

  119.         } else if (part.isMimeType("message/rfc822")) {   

  120.             getMailContent((Part) part.getContent());   

  121.         } else {}   

  122.     }   

  123.     /**   

  124.      * 判断此邮件是否需要回执,如果需要回执返回"true",否则返回"false"

  125.      */   

  126.     public boolean getReplySign() throws MessagingException {   

  127.         boolean replysign = false;   

  128.         String needreply[] = mimeMessage   

  129.                 .getHeader("Disposition-Notification-To");   

  130.         if (needreply != null) {   

  131.             replysign = true;   

  132.         }   

  133.         return replysign;   

  134.     }   

  135.     /**

  136.      * 获得此邮件的Message-ID

  137.      */

  138.     public String getMessageId() throws MessagingException {   

  139.         return mimeMessage.getMessageID();   

  140.     }   

  141.     /**

  142.      * 【判断此邮件是否已读,如果未读返回返回false,反之返回true】

  143.      */

  144.     public boolean isNew() throws MessagingException {   

  145.         boolean isnew = false;   

  146.         Flags flags = ((Message) mimeMessage).getFlags();   

  147.         Flags.Flag[] flag = flags.getSystemFlags();   

  148.         System.out.println("flags's length: " + flag.length);   

  149.         for (int i = 0; i < flag.length; i++) {   

  150.             if (flag[i] == Flags.Flag.SEEN) {   

  151.                 isnew = true;   

  152.                 System.out.println("seen Message.......");   

  153.                 break;   

  154.             }   

  155.         }   

  156.         return isnew;   

  157.     }   

  158.     /**

  159.      * 判断此邮件是否包含附件

  160.      */

  161.     public boolean isContainAttach(Part part) throws Exception {   

  162.         boolean attachflag = false;   

  163.         String contentType = part.getContentType();   

  164.         if (part.isMimeType("multipart/*")) {   

  165.             Multipart mp = (Multipart) part.getContent();   

  166.             for (int i = 0; i < mp.getCount(); i++) {   

  167.                 BodyPart mpart = mp.getBodyPart(i);   

  168.                 String disposition = mpart.getDisposition();   

  169.                 if ((disposition != null)   

  170.                         && ((disposition.equals(Part.ATTACHMENT)) || (disposition   

  171.                                 .equals(Part.INLINE))))   

  172.                     attachflag = true;   

  173.                 else if (mpart.isMimeType("multipart/*")) {   

  174.                     attachflag = isContainAttach((Part) mpart);   

  175.                 } else {   

  176.                     String contype = mpart.getContentType();   

  177.                     if (contype.toLowerCase().indexOf("application") != -1)   

  178.                         attachflag = true;   

  179.                     if (contype.toLowerCase().indexOf("name") != -1)   

  180.                         attachflag = true;   

  181.                 }   

  182.             }   

  183.         } else if (part.isMimeType("message/rfc822")) {   

  184.             attachflag = isContainAttach((Part) part.getContent());   

  185.         }   

  186.         return attachflag;   

  187.     }   

  188.     /**   

  189.      * 【保存附件】   

  190.      */   

  191.     public void saveAttachMent(Part part) throws Exception {   

  192.         String fileName = "";   

  193.         if (part.isMimeType("multipart/*")) {   

  194.             Multipart mp = (Multipart) part.getContent();   

  195.             for (int i = 0; i < mp.getCount(); i++) {   

  196.                 BodyPart mpart = mp.getBodyPart(i);   

  197.                 String disposition = mpart.getDisposition();   

  198.                 if ((disposition != null)   

  199.                         && ((disposition.equals(Part.ATTACHMENT)) || (disposition   

  200.                                 .equals(Part.INLINE)))) {   

  201.                     fileName = mpart.getFileName();   

  202.                     if (fileName.toLowerCase().indexOf("gb2312") != -1) {   

  203.                         fileName = MimeUtility.decodeText(fileName);   

  204.                     }   

  205.                     saveFile(fileName, mpart.getInputStream());   

  206.                 } else if (mpart.isMimeType("multipart/*")) {   

  207.                     saveAttachMent(mpart);   

  208.                 } else {   

  209.                     fileName = mpart.getFileName();   

  210.                     if ((fileName != null)   

  211.                             && (fileName.toLowerCase().indexOf("GB2312") != -1)) {   

  212.                         fileName = MimeUtility.decodeText(fileName);   

  213.                         saveFile(fileName, mpart.getInputStream());   

  214.                     }   

  215.                 }   

  216.             }   

  217.         } else if (part.isMimeType("message/rfc822")) {   

  218.             saveAttachMent((Part) part.getContent());   

  219.         }   

  220.     }   

  221.     /**   

  222.      * 【设置附件存放路径】   

  223.      */   

  224.     public void setAttachPath(String attachpath) {   

  225.         this.saveAttachPath = attachpath;   

  226.     }   

  227.     /**

  228.      * 【设置日期显示格式】

  229.      */

  230.     public void setDateFormat(String format) throws Exception {   

  231.         this.dateformat = format;   

  232.     }   

  233.     /**

  234.      * 【获得附件存放路径】

  235.      */

  236.     public String getAttachPath() {   

  237.         return saveAttachPath;   

  238.     }   

  239.     /**

  240.      * 【真正的保存附件到指定目录里】

  241.      */

  242.     private void saveFile(String fileName, InputStream in) throws Exception {   

  243.         String osName = System.getProperty("os.name");   

  244.         String storedir = getAttachPath();   

  245.         String separator = "";   

  246.         if (osName == null)   

  247.             osName = "";   

  248.         if (osName.toLowerCase().indexOf("win") != -1) {   

  249.             separator = "\\\\";

  250.             if (storedir == null || storedir.equals(""))

  251.                 storedir = "c:\\\\tmp";

  252.         } else {

  253.             separator = "/";

  254.             storedir = "/tmp";

  255.         }

  256.         File storefile = new File(storedir + separator + fileName);

  257.         System.out.println("storefile's path: " + storefile.toString());

  258.         // for(int i=0;storefile.exists();i++){

  259.         // storefile = new File(storedir+separator+fileName+i);

  260.         // }

  261.         BufferedOutputStream bos = null;

  262.         BufferedInputStream bis = null;

  263.         try {

  264.             bos = new BufferedOutputStream(new FileOutputStream(storefile));

  265.             bis = new BufferedInputStream(in);

  266.             int c;

  267.             while ((c = bis.read()) != -1) {

  268.                 bos.write(c);

  269.                 bos.flush();

  270.             }

  271.         } catch (Exception exception) {

  272.             exception.printStackTrace();

  273.             throw new Exception("文件保存失败!");

  274.         } finally {

  275.             bos.close();

  276.             bis.close();

  277.         }

  278.     }

  279.  

  280.     /**

  281.      * PraseMimeMessage类测试

  282.      */

  283.     public static void main(String args[]) throws Exception {

  284.         Properties props = System.getProperties();

  285.         props.put("mail.smtp.host", "smtp.163.com");

  286.         props.put("mail.smtp.auth", "true");

  287.         Session session = Session.getDefaultInstance(props, null);

  288.         URLName urln = new URLName("pop3", "pop3.163.com", 110, null,

  289.                 "xiangzhengyan", "pass");

  290.         Store store = session.getStore(urln);

  291.         store.connect();

  292.         Folder folder = store.getFolder("INBOX");

  293.         folder.open(Folder.READ_ONLY);

  294.         Message message[] = folder.getMessages();

  295.         System.out.println("Messages's length: " + message.length);

  296.         ReciveOneMail pmm = null;

  297.         for (int i = 0; i < message.length; i++) {

  298.             System.out.println("======================");

  299.             pmm = new ReciveOneMail((MimeMessage) message[i]);

  300.             System.out.println("Message " + i + " subject: " + pmm.getSubject());

  301.             System.out.println("Message " + i + " sentdate: "+ pmm.getSentDate());

  302.             System.out.println("Message " + i + " replysign: "+ pmm.getReplySign());

  303.             System.out.println("Message " + i + " hasRead: " + pmm.isNew());

  304.             System.out.println("Message " + i + "  containAttachment: "+ pmm.isContainAttach((Part) message[i]));

  305.             System.out.println("Message " + i + " form: " + pmm.getFrom());

  306.             System.out.println("Message " + i + " to: "+ pmm.getMailAddress("to"));

  307.             System.out.println("Message " + i + " cc: "+ pmm.getMailAddress("cc"));

  308.             System.out.println("Message " + i + " bcc: "+ pmm.getMailAddress("bcc"));

  309.             pmm.setDateFormat("yy年MM月dd日 HH:mm");

  310.             System.out.println("Message " + i + " sentdate: "+ pmm.getSentDate());

  311.             System.out.println("Message " + i + " Message-ID: "+ pmm.getMessageId());

  312.             // 获得邮件内容===============

  313.             pmm.getMailContent((Part) message[i]);

  314.             System.out.println("Message " + i + " bodycontent: \\r\\n"

  315.                     + pmm.getBodyText());

  316.             pmm.setAttachPath("c:\\\\");   

  317.             pmm.saveAttachMent((Part) message[i]);   

  318.         }   

  319.     }   

  320. }  

   

分享到:       sina.jpg\"       tec.jpg\"    

第一个Hibernate with Annotation程式(转 ...      |       javamail发送邮件(简)    

评论

   

14 楼     hsjshijiazhuang    2014-03-03  

另外再指出,此程序针对于windows vista 以上系统,c盘是拒绝访问的,所以还得在其它盘符下创建附件文件,或者获得访问权限icon_biggrin.gif\"

13 楼     hsjshijiazhuang    2014-03-03  

这里面有错误,我修改了,具体修改是:第216行中,if语句中增加((fileName != null)),第219行的saveFile方法挪到if语句里面。就不会报错了

12 楼     llxiyuel    2014-03-01  

大哥,怎么解析邮件正文输出纯文本

11 楼     yiwanxinyuefml    2014-01-26  

请教一个问题,不知道其他人有没碰到过:就是用javamail接收的邮件,正文、附件都可以正常接收,但是邮件正文有一些换行符之类的东西,接收到之后写入到一个文件却是一整串没有换行符的字符串???

10 楼     amwyyyy    2013-11-29  

不错不错icon_biggrin.gif\" icon_biggrin.gif\" icon_biggrin.gif\" icon_biggrin.gif\"

9 楼     spy41s    2013-07-23  

中文会乱码。。。

8 楼     tigerwood008    2012-01-07  

如果有附件的哈,好像会有内存溢出的问题,这个该怎么解决!

7 楼     fuanyu    2011-10-14  

确实比较全  但是我试了  邮件内容部分还是有问题耶 能否再详细解说下哦

6 楼     嘻哈方式     2011-05-26  

确实比较全  但是我试了  邮件内容部分还是有问题耶 能否再详细解说下哦

5 楼     zyh_1986    2010-09-21  

写得真不错!从里面学到不少网上很难找的东西,多谢……

4 楼     bsspirit    2010-08-12  

这个不错,很有帮助!!

3 楼     DepthJava    2010-04-12  

封装的很不错,乱码问题怎么解决的?

2 楼     containsoft    2009-11-23  

大哥,问你个问题,邮件收取进来,并保存为文件之后,要在web页面里一条一条的显示出邮件的日期,标题,发件人,点击进去,查看邮件具体内容,这该怎么做呢。能指点指点么。我邮箱containsoft@163.com

1 楼     maweiqiang    2008-06-04  

你好啊,你的这个接受邮件我看了,确实写的很不错啊,我们老师也让我们做一个收发邮件,但是收邮件这里我不太明白,麻烦你能把你收邮件的代码包括页面给我看下吗。非常感谢啊,大哥我的邮箱是maweiqiang1025@163.com

发表评论

login_icon.png\"  您还没有登录,请您登录后再发表评论

\"xiangzhengyan的博客\"

xiangzhengyan

  • 浏览: 63611 次

  • 性别: \"Icon_minigender_1\"

  • 来自: 北京

  • offline.gif\"

最近访客 更多访客>>

\"dylinshi126的博客\"

dylinshi126

\"shuitao.cao的博客\"

shuitao.cao

\"smile_clj的博客\"

smile_clj

\"Hundun_Wu的博客\"

Hundun_Wu

文章分类
社区版块
存档分类
最新评论

声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。若作者同意转载,必须以超链接形式标明文章原始出处和作者。
2003-2014 ITeye.com.   All rights reserved.  [ 京ICP证110151号  京公网安备110105010620 ]

?url=http%3A%2F%2Fxiangzhengyan.iteye.co