注意邮件协议 详细如下
http://baike.baidu.com/view/2367542.htm?fr=aladdin
发送邮件是stmp协议
邮件接收可以是pop3或者imap
1 pop3邮件实现
import java.util.Properties;
import java.util.Scanner;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
public class ReceivEmail {
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
prop.setProperty("mail.store.protocol", "pop3");//邮件协议
prop.setProperty("ail.pop3.host", "pop.163.com");//收取邮件协议
Session session = Session.getDefaultInstance(prop,null);//获取与服务器之间的会话连接
session.setDebug(false);
Store store = session.getStore();//会话获取Store对象
store.connect("pop.163.com","y****", "******");
Folder folder = store.getFolder("Inbox"); //打开inbox文件夹
folder.open(Folder.READ_WRITE);//读写方式
Message[] messages = folder.getMessages();
for(int i = 0 ;i<messages.length;i++){
String from = "";
System.out.println("第" + (i+1) +"封邮件,主题是:" + messages[i].getSubject() +" 地址是:" + from );
System.out.println("你想阅读此邮件么(y/n)?");
Scanner scan = new Scanner(System.in);
String s =scan.next();
if(s.trim().equals("y")){
String tempstr = messages[i].getContent().toString();
System.out.println(tempstr);
}
}
folder.close(false);
store.close();
}
}
2 imap邮件实现
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeUtility;
import com.sun.mail.imap.IMAPMessage;
public class ReceivEmail {
public static void main(String[] args) throws Exception { // 准备连接服务器的会话信息
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imap");
props.setProperty("mail.imap.host", "imap.163.com");
props.setProperty("mail.imap.port", "143");
// 创建Session实例对象
Session session = Session.getInstance(props);
// 创建IMAP协议的Store对象
Store store = session.getStore("imap");
// 连接邮件服务器
store.connect("y****@163.com", "****");
// 获得收件箱
Folder folder = store.getFolder("INBOX");
// 以读写模式打开收件箱
folder.open(Folder.READ_WRITE);
// 获得收件箱的邮件列表
Message[] messages = folder.getMessages();
// 打印不同状态的邮件数量
System.out.println("收件箱中共" + messages.length + "封邮件!");
System.out.println("收件箱中共" + folder.getUnreadMessageCount() + "封未读邮件!");
System.out.println("收件箱中共" + folder.getNewMessageCount() + "封新邮件!");
System.out.println("收件箱中共" + folder.getDeletedMessageCount() + "封已删除邮件!");
System.out.println("------------------------开始解析邮件----------------------------------");
// 解析邮件
for (Message message : messages) {
IMAPMessage msg = (IMAPMessage) message;
String subject = MimeUtility.decodeText(msg.getSubject());
System.out.println("[" + subject + "]未读,是否需要阅读此邮件(yes/no)?");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String answer = reader.readLine();
}
// 关闭资源
folder.close(false);
store.close();
}
}