javamail接收邮件(zt)
zt from:http://xiangzhengyan.iteye.com/blog/85961
- 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.*;
- import java.text.*;
- import java.util.*;
- import javax.mail.*;
- import javax.mail.internet.*;
- /**
- * 有一封邮件就需要建立一个ReciveMail对象
- */
- public class ReciveOneMail {
- private MimeMessage mimeMessage = null;
- private String saveAttachPath = ""; //附件下载后的存放目录
- private StringBuffer bodytext = new StringBuffer();//存放邮件内容
- private String dateformat = "yy-MM-dd HH:mm"; //默认的日前显示格式
- public ReciveOneMail(MimeMessage mimeMessage) {
- this.mimeMessage = mimeMessage;
- }
- public void setMimeMessage(MimeMessage mimeMessage) {
- this.mimeMessage = mimeMessage;
- }
- /**
- * 获得发件人的地址和姓名
- */
- public String getFrom() throws Exception {
- InternetAddress address[] = (InternetAddress[]) mimeMessage.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;
- }
- /**
- * 获得邮件的收件人,抄送,和密送的地址和姓名,根据所传递的参数的不同 "to"----收件人 "cc"---抄送人地址 "bcc"---密送人地址
- */
- public String getMailAddress(String type) throws Exception {
- String mailaddr = "";
- String addtype = type.toUpperCase();
- InternetAddress[] address = null;
- if (addtype.equals("TO") || addtype.equals("CC")|| addtype.equals("BCC")) {
- if (addtype.equals("TO")) {
- address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.TO);
- } else if (addtype.equals("CC")) {
- address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.CC);
- } else {
- address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.BCC);
- }
- if (address != null) {
- for (int i = 0; i < address.length; i++) {
- String email = address[i].getAddress();
- if (email == null)
- email = "";
- else {
- email = MimeUtility.decodeText(email);
- }
- String personal = address[i].getPersonal();
- if (personal == null)
- personal = "";
- else {
- personal = MimeUtility.decodeText(personal);
- }
- String compositeto = personal + "<" + email + ">";
- mailaddr += "," + compositeto;
- }
- mailaddr = mailaddr.substring(1);
- }
- } else {
- throw new Exception("Error emailaddr type!");
- }
- return mailaddr;
- }
- /**
- * 获得邮件主题
- */
- public String getSubject() throws MessagingException {
- String subject = "";
- try {
- subject = MimeUtility.decodeText(mimeMessage.getSubject());
- if (subject == null)
- subject = "";
- } catch (Exception exce) {}
- return subject;
- }
- /**
- * 获得邮件发送日期
- */
- public String getSentDate() throws Exception {
- Date sentdate = mimeMessage.getSentDate();
- SimpleDateFormat format = new SimpleDateFormat(dateformat);
- return format.format(sentdate);
- }
- /**
- * 获得邮件正文内容
- */
- public String getBodyText() {
- return bodytext.toString();
- }
- /**
- * 解析邮件,把得到的邮件内容保存到一个StringBuffer对象中,解析邮件 主要是根据MimeType类型的不同执行不同的操作,一步一步的解析
- */
- public void getMailContent(Part part) throws Exception {
- 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 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 {}
- }
- /**
- * 判断此邮件是否需要回执,如果需要回执返回"true",否则返回"false"
- */
- public boolean getReplySign() throws MessagingException {
- boolean replysign = false;
- String needreply[] = mimeMessage
- .getHeader("Disposition-Notification-To");
- if (needreply != null) {
- replysign = true;
- }
- return replysign;
- }
- /**
- * 获得此邮件的Message-ID
- */
- public String getMessageId() throws MessagingException {
- return mimeMessage.getMessageID();
- }
- /**
- * 【判断此邮件是否已读,如果未读返回返回false,反之返回true】
- */
- public boolean isNew() throws MessagingException {
- boolean isnew = false;
- Flags flags = ((Message) mimeMessage).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;
- }
- /**
- * 判断此邮件是否包含附件
- */
- public boolean isContainAttach(Part part) throws Exception {
- boolean attachflag = false;
- String contentType = part.getContentType();
- if (part.isMimeType("multipart/*")) {
- Multipart mp = (Multipart) part.getContent();
- for (int i = 0; i < mp.getCount(); i++) {
- BodyPart mpart = mp.getBodyPart(i);
- String disposition = mpart.getDisposition();
- if ((disposition != null)
- && ((disposition.equals(Part.ATTACHMENT)) || (disposition
- .equals(Part.INLINE))))
- attachflag = true;
- else if (mpart.isMimeType("multipart/*")) {
- attachflag = isContainAttach((Part) mpart);
- } else {
- String contype = mpart.getContentType();
- if (contype.toLowerCase().indexOf("application") != -1)
- attachflag = true;
- if (contype.toLowerCase().indexOf("name") != -1)
- attachflag = true;
- }
- }
- } else if (part.isMimeType("message/rfc822")) {
- attachflag = isContainAttach((Part) part.getContent());
- }
- return attachflag;
- }
- /**
- * 【保存附件】
- */
- public void saveAttachMent(Part part) throws Exception {
- 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 disposition = mpart.getDisposition();
- if ((disposition != null)
- && ((disposition.equals(Part.ATTACHMENT)) || (disposition
- .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/*")) {
- saveAttachMent(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")) {
- saveAttachMent((Part) part.getContent());
- }
- }
- /**
- * 【设置附件存放路径】
- */
- public void setAttachPath(String attachpath) {
- this.saveAttachPath = attachpath;
- }
- /**
- * 【设置日期显示格式】
- */
- public void setDateFormat(String format) throws Exception {
- this.dateformat = format;
- }
- /**
- * 【获得附件存放路径】
- */
- public String getAttachPath() {
- return saveAttachPath;
- }
- /**
- * 【真正的保存附件到指定目录里】
- */
- private void saveFile(String fileName, InputStream in) throws Exception {
- String osName = System.getProperty("os.name");
- String storedir = getAttachPath();
- 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 + fileName);
- System.out.println("storefile's path: " + storefile.toString());
- // for(int i=0;storefile.exists();i++){
- // storefile = new File(storedir+separator+fileName+i);
- // }
- BufferedOutputStream bos = null;
- BufferedInputStream bis = null;
- try {
- bos = new BufferedOutputStream(new FileOutputStream(storefile));
- bis = new BufferedInputStream(in);
- int c;
- while ((c = bis.read()) != -1) {
- bos.write(c);
- bos.flush();
- }
- } catch (Exception exception) {
- exception.printStackTrace();
- throw new Exception("文件保存失败!");
- } finally {
- bos.close();
- bis.close();
- }
- }
- /**
- * PraseMimeMessage类<a href="http://lib.csdn.net/base/softwaretest" class='replace_word' title="软件测试知识库" target='_blank' style='color:#df3434; font-weight:bold;'>测试</a>
- */
- public static void main(String args[]) throws Exception {
- Properties props = System.getProperties();
- props.put("mail.smtp.host", "smtp.163.com");
- props.put("mail.smtp.auth", "true");
- Session session = Session.getDefaultInstance(props, null);
- URLName urln = new URLName("pop3", "pop3.163.com", 110, null,
- "xiangzhengyan", "pass");
- Store store = session.getStore(urln);
- store.connect();
- Folder folder = store.getFolder("INBOX");
- folder.open(Folder.READ_ONLY);
- Message message[] = folder.getMessages();
- System.out.println("Messages's length: " + message.length);
- ReciveOneMail pmm = null;
- for (int i = 0; i < message.length; i++) {
- System.out.println("======================");
- pmm = new ReciveOneMail((MimeMessage) message[i]);
- System.out.println("Message " + i + " subject: " + pmm.getSubject());
- System.out.println("Message " + i + " sentdate: "+ pmm.getSentDate());
- System.out.println("Message " + i + " replysign: "+ pmm.getReplySign());
- System.out.println("Message " + i + " hasRead: " + pmm.isNew());
- System.out.println("Message " + i + " containAttachment: "+ pmm.isContainAttach((Part) message[i]));
- System.out.println("Message " + i + " form: " + pmm.getFrom());
- System.out.println("Message " + i + " to: "+ pmm.getMailAddress("to"));
- System.out.println("Message " + i + " cc: "+ pmm.getMailAddress("cc"));
- System.out.println("Message " + i + " bcc: "+ pmm.getMailAddress("bcc"));
- pmm.setDateFormat("yy年MM月dd日 HH:mm");
- System.out.println("Message " + i + " sentdate: "+ pmm.getSentDate());
- System.out.println("Message " + i + " Message-ID: "+ pmm.getMessageId());
- // 获得邮件内容===============
- pmm.getMailContent((Part) message[i]);
- System.out.println("Message " + i + " bodycontent: /r/n"
- + pmm.getBodyText());
- pmm.setAttachPath("c://");
- pmm.saveAttachMent((Part) message[i]);
- }
- }
- }
javamail接收邮件(zt)的更多相关文章
- JavaMail 接收邮件及删除
解析读取收件箱中邮件: import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io. ...
- 邮件实现详解(四)------JavaMail 发送(带图片和附件)和接收邮件
好了,进入这个系列教程最主要的步骤了,前面邮件的理论知识我们都了解了,那么这篇博客我们将用代码完成邮件的发送.这在实际项目中应用的非常广泛,比如注册需要发送邮件进行账号激活,再比如OA项目中利用邮件进 ...
- JavaMail入门第四篇 接收邮件
上一篇JavaMail入门第三篇 发送邮件中,我们学会了如何用JavaMail API提供的Transport类发送邮件,同样,JavaMail API中也提供了一些专门的类来对邮件的接收进行相关的操 ...
- JavaMail发送和接收邮件API(详解)
一.JavaMail概述: JavaMail是由Sun定义的一套收发电子邮件的API,不同的厂商可以提供自己的实现类.但它并没有包含在JDK中,而是作为JavaEE的一部分. 厂商所提供的JavaMa ...
- Android Java使用JavaMail API发送和接收邮件的代码示例
JavaMail是Oracle甲骨文开发的Java邮件类API,支持多种邮件协议,这里我们就来看一下Java使用JavaMail API发送和接收邮件的代码示例 使用Javamail发送邮件,必需的j ...
- Android javaMail使用imap协议接收邮件
在这里说明一下,pop3和imap协议都是接收邮件的,但是他们还是有很多不同的. IMAP和POP有什么区别? POP允许电子邮件客户端下载服务器上的邮件,但是您在电子邮件客户端的操作(如:移动邮件. ...
- 基于JavaMail开发邮件发送器工具类
基于JavaMail开发邮件发送器工具类 在开发当中肯定会碰到利用Java调用邮件服务器的服务发送邮件的情况,比如账号激活.找回密码等功能.本人之前也碰到多次这样需求,为此特意将功能封装成一个简单易用 ...
- javamail发邮件
使用JavaMail发送一封简单邮件的步骤:(1)创建代表邮件服务器的网络连接信息的Session对象.(2)创建代表邮件内容的Message对象(3)创建Transport对象.连接服务器.发送Me ...
- javaMail发邮件,激活用户账号
用javamail实现注册用户验证邮箱功能.用户注册后随机生成一个uuid作为用户的标识,传递给用户然后作为路径参数.发送html的内容到用户注册的邮箱里,若用户点击后去往的页面提交username和 ...
随机推荐
- UNIX网络编程——套接字选项(SOL_SOCKET级别)
#include <sys/socket.h> int setsockopt( int socket, int level, int option_name,const void *opt ...
- Douglas Adams - 3 Rules That Describe Our Reactions To Technologies 科技影响生活的三个规律
文章摘自http://highscalability.com/. 这个博客是大家都应该订阅的.原文地址http://highscalability.com/blog/2014/3/11/douglas ...
- 使用Mediaplay类写一个播放器
我们知道android本身播放视频的的能力是有限的..先来一个Demo 另附我的一个还未成熟的播放器,下载地址:http://www.eoemarket.com/soft/370334.html,正在 ...
- iOS中大流中的自定义cell 技术分享
AppDelegate.m指定根视图 self.window.rootViewController = [[UINavigationController alloc] initWithRootView ...
- win7 VMware CentOS桥接(bridge)模式网络配置
主要内容参考自: centos下vmware 桥接设置静态ip例子 关于虚拟机网络配置的文章: Win7+VMware Workstation环境下的CentOS-Linux网络连接设置(推荐阅读) ...
- Cocos2D旋转炮塔到指定角度(三)
到目前为止都很美好! 但是却有一点奇怪,因为炮塔一下子跳转到指定位置去射击,并不是平滑的跟随触摸去转动到指定位置.你可以修复这个问题,但是这需要略微一点的重构(refactoring). 首先打开He ...
- JAVA数组的定义以及使用1
public class HelloWorld { public static void main(String[] args){ // Scanner s = new Scanner(System. ...
- Socket层实现系列 — 睡眠驱动的同步等待
主要内容:Socket的同步等待机制,connect和accept等待的实现. 内核版本:3.15.2 我的博客:http://blog.csdn.net/zhangskd 概述 socket上定义了 ...
- C语言通讯录管理系统
本文转载自:http://blog.csdn.net/hackbuteer1/article/details/6573488 实现了通讯录的录入信息.保存信息.插入.删除.排序.查找.单个显示等功能. ...
- avcodec_decode_video2()解码视频后丢帧的问题解决
使用libav转码视频时发现一个问题:使用下面这段代码解码视频时,视频尾巴上会丢掉几帧. while(av_read_frame(ifmt_ctx,&packet) >= 0){ ret ...