zt from:http://xiangzhengyan.iteye.com/blog/85961

  1. import <a href="http://lib.csdn.net/base/java" class='replace_word' title="Java 知识库" target='_blank' style='color:#df3434; font-weight:bold;'>Java</a>.io.*;
  2. import java.text.*;
  3. import java.util.*;
  4. import javax.mail.*;
  5. import javax.mail.internet.*;
  6.  
  7. /**
  8. * 有一封邮件就需要建立一个ReciveMail对象
  9. */
  10. public class ReciveOneMail {
  11. private MimeMessage mimeMessage = null;
  12. private String saveAttachPath = ""; //附件下载后的存放目录
  13. private StringBuffer bodytext = new StringBuffer();//存放邮件内容
  14. private String dateformat = "yy-MM-dd HH:mm"; //默认的日前显示格式
  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. * 获得发件人的地址和姓名
  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. * 获得邮件的收件人,抄送,和密送的地址和姓名,根据所传递的参数的不同 "to"----收件人 "cc"---抄送人地址 "bcc"---密送人地址
  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. * 获得邮件主题
  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. * 获得邮件发送日期
  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. * 获得邮件正文内容
  103. */
  104. public String getBodyText() {
  105. return bodytext.toString();
  106. }
  107.  
  108. /**
  109. * 解析邮件,把得到的邮件内容保存到一个StringBuffer对象中,解析邮件 主要是根据MimeType类型的不同执行不同的操作,一步一步的解析
  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. * 判断此邮件是否需要回执,如果需要回执返回"true",否则返回"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. * 获得此邮件的Message-ID
  148. */
  149. public String getMessageId() throws MessagingException {
  150. return mimeMessage.getMessageID();
  151. }
  152.  
  153. /**
  154. * 【判断此邮件是否已读,如果未读返回返回false,反之返回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. * 判断此邮件是否包含附件
  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. * 【保存附件】
  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. * 【设置附件存放路径】
  238. */
  239.  
  240. public void setAttachPath(String attachpath) {
  241. this.saveAttachPath = attachpath;
  242. }
  243.  
  244. /**
  245. * 【设置日期显示格式】
  246. */
  247. public void setDateFormat(String format) throws Exception {
  248. this.dateformat = format;
  249. }
  250.  
  251. /**
  252. * 【获得附件存放路径】
  253. */
  254. public String getAttachPath() {
  255. return saveAttachPath;
  256. }
  257.  
  258. /**
  259. * 【真正的保存附件到指定目录里】
  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("文件保存失败!");
  293. } finally {
  294. bos.close();
  295. bis.close();
  296. }
  297. }
  298.  
  299. /**
  300. * PraseMimeMessage类<a href="http://lib.csdn.net/base/softwaretest" class='replace_word' title="软件测试知识库" target='_blank' style='color:#df3434; font-weight:bold;'>测试</a>
  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月dd日 HH:mm");
  329. System.out.println("Message " + i + " sentdate: "+ pmm.getSentDate());
  330. System.out.println("Message " + i + " Message-ID: "+ pmm.getMessageId());
  331. // 获得邮件内容===============
  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接收邮件(zt)的更多相关文章

  1. JavaMail 接收邮件及删除

    解析读取收件箱中邮件: import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io. ...

  2. 邮件实现详解(四)------JavaMail 发送(带图片和附件)和接收邮件

    好了,进入这个系列教程最主要的步骤了,前面邮件的理论知识我们都了解了,那么这篇博客我们将用代码完成邮件的发送.这在实际项目中应用的非常广泛,比如注册需要发送邮件进行账号激活,再比如OA项目中利用邮件进 ...

  3. JavaMail入门第四篇 接收邮件

    上一篇JavaMail入门第三篇 发送邮件中,我们学会了如何用JavaMail API提供的Transport类发送邮件,同样,JavaMail API中也提供了一些专门的类来对邮件的接收进行相关的操 ...

  4. JavaMail发送和接收邮件API(详解)

    一.JavaMail概述: JavaMail是由Sun定义的一套收发电子邮件的API,不同的厂商可以提供自己的实现类.但它并没有包含在JDK中,而是作为JavaEE的一部分. 厂商所提供的JavaMa ...

  5. Android Java使用JavaMail API发送和接收邮件的代码示例

    JavaMail是Oracle甲骨文开发的Java邮件类API,支持多种邮件协议,这里我们就来看一下Java使用JavaMail API发送和接收邮件的代码示例 使用Javamail发送邮件,必需的j ...

  6. Android javaMail使用imap协议接收邮件

    在这里说明一下,pop3和imap协议都是接收邮件的,但是他们还是有很多不同的. IMAP和POP有什么区别? POP允许电子邮件客户端下载服务器上的邮件,但是您在电子邮件客户端的操作(如:移动邮件. ...

  7. 基于JavaMail开发邮件发送器工具类

    基于JavaMail开发邮件发送器工具类 在开发当中肯定会碰到利用Java调用邮件服务器的服务发送邮件的情况,比如账号激活.找回密码等功能.本人之前也碰到多次这样需求,为此特意将功能封装成一个简单易用 ...

  8. javamail发邮件

    使用JavaMail发送一封简单邮件的步骤:(1)创建代表邮件服务器的网络连接信息的Session对象.(2)创建代表邮件内容的Message对象(3)创建Transport对象.连接服务器.发送Me ...

  9. javaMail发邮件,激活用户账号

    用javamail实现注册用户验证邮箱功能.用户注册后随机生成一个uuid作为用户的标识,传递给用户然后作为路径参数.发送html的内容到用户注册的邮箱里,若用户点击后去往的页面提交username和 ...

随机推荐

  1. UNIX网络编程——套接字选项(SOL_SOCKET级别)

    #include <sys/socket.h> int setsockopt( int socket, int level, int option_name,const void *opt ...

  2. Douglas Adams - 3 Rules That Describe Our Reactions To Technologies 科技影响生活的三个规律

    文章摘自http://highscalability.com/. 这个博客是大家都应该订阅的.原文地址http://highscalability.com/blog/2014/3/11/douglas ...

  3. 使用Mediaplay类写一个播放器

    我们知道android本身播放视频的的能力是有限的..先来一个Demo 另附我的一个还未成熟的播放器,下载地址:http://www.eoemarket.com/soft/370334.html,正在 ...

  4. iOS中大流中的自定义cell 技术分享

    AppDelegate.m指定根视图 self.window.rootViewController = [[UINavigationController alloc] initWithRootView ...

  5. win7 VMware CentOS桥接(bridge)模式网络配置

    主要内容参考自: centos下vmware 桥接设置静态ip例子 关于虚拟机网络配置的文章: Win7+VMware Workstation环境下的CentOS-Linux网络连接设置(推荐阅读) ...

  6. Cocos2D旋转炮塔到指定角度(三)

    到目前为止都很美好! 但是却有一点奇怪,因为炮塔一下子跳转到指定位置去射击,并不是平滑的跟随触摸去转动到指定位置.你可以修复这个问题,但是这需要略微一点的重构(refactoring). 首先打开He ...

  7. JAVA数组的定义以及使用1

    public class HelloWorld { public static void main(String[] args){ // Scanner s = new Scanner(System. ...

  8. Socket层实现系列 — 睡眠驱动的同步等待

    主要内容:Socket的同步等待机制,connect和accept等待的实现. 内核版本:3.15.2 我的博客:http://blog.csdn.net/zhangskd 概述 socket上定义了 ...

  9. C语言通讯录管理系统

    本文转载自:http://blog.csdn.net/hackbuteer1/article/details/6573488 实现了通讯录的录入信息.保存信息.插入.删除.排序.查找.单个显示等功能. ...

  10. avcodec_decode_video2()解码视频后丢帧的问题解决

    使用libav转码视频时发现一个问题:使用下面这段代码解码视频时,视频尾巴上会丢掉几帧. while(av_read_frame(ifmt_ctx,&packet) >= 0){ ret ...