少年阿賓

          那些青春的歲月

            BlogJava :: 首頁 :: 聯系 :: 聚合  :: 管理
            500 Posts :: 0 Stories :: 135 Comments :: 0 Trackbacks

          #

          在上網的時候,我們經常會看到“端口”這個詞,也會經常用到端口號,比如在FTP地址后面增加的“21”,21就表示端口號。那么端口到底是什么意思呢?怎樣查看端口號呢?一個端口是否成為網絡惡意攻擊的大門呢?,我們應該如何面對形形色色的端口呢?下面就將介紹這方面的內容,以供大家參考。

          21端口:21端口主要用于FTP(File Transfer Protocol,文件傳輸協議)服務。

          端口說明:21端口主要用于FTP(File Transfer Protocol,文件傳輸協議)服務,FTP服務主要是為了在兩臺計算機之間實現文件的上傳與下載,一臺計算機作為FTP客戶端,另一臺計算機作為FTP服務器,可以采用匿名(anonymous)登錄和授權用戶名與密碼登錄兩種方式登錄FTP服務器。目前,通過FTP服務來實現文件的傳輸是互聯網上上傳、下載文件最主要的方法。另外,還有一個20端口是用于FTP數據傳輸的默認端口號。

          在Windows中可以通過Internet信息服務(IIS)來提供FTP連接和管理,也可以單獨安裝FTP服務器軟件來實現FTP功能,比如常見的FTP Serv-U。

          操作建議:因為有的FTP服務器可以通過匿名登錄,所以常常會被黑客利用。另外,21端口還會被一些木馬利用,比如Blade Runner、FTP Trojan、Doly Trojan、WebEx等等。如果不架設FTP服務器,建議關閉21端口。

          23端口:23端口主要用于Telnet(遠程登錄)服務,是Internet上普遍采用的登錄和仿真程序。

          端口說明:23端口主要用于Telnet(遠程登錄)服務,是Internet上普遍采用的登錄和仿真程序。同樣需要設置客戶端和服務器端,開啟Telnet服務的客戶端就可以登錄遠程Telnet服務器,采用授權用戶名和密碼登錄。登錄之后,允許用戶使用命令提示符窗口進行相應的操作。在Windows中可以在命令提示符窗口中,鍵入“Telnet”命令來使用Telnet遠程登錄。

          操作建議:利用Telnet服務,黑客可以搜索遠程登錄Unix的服務,掃描操作系統的類型。而且在Windows 2000中Telnet服務存在多個嚴重的漏洞,比如提升權限、拒絕服務等,可以讓遠程服務器崩潰。Telnet服務的23端口也是TTS(Tiny Telnet Server)木馬的缺省端口。所以,建議關閉23端口。


          25端口:25端口為SMTP(Simple Mail Transfer Protocol,簡單郵件傳輸協議)服務器所開放,主要用于發送郵件,如今絕大多數郵件服務器都使用該協議。

          端口說明:25端口為SMTP(Simple Mail Transfer Protocol,簡單郵件傳輸協議)服務器所開放,主要用于發送郵件,如今絕大多數郵件服務器都使用該協議。比如我們在使用電子郵件客戶端程序的時候,在創建賬戶時會要求輸入SMTP服務器地址,該服務器地址默認情況下使用的就是25端口。

          端口漏洞:

          1. 利用25端口,黑客可以尋找SMTP服務器,用來轉發垃圾郵件。

          2. 25端口被很多木馬程序所開放,比如Ajan、Antigen、Email Password Sender、ProMail、trojan、Tapiras、Terminator、WinPC、WinSpy等等。拿WinSpy來說,通過開放25端口,可以監視計算機正在運行的所有窗口和模塊。

          操作建議:如果不是要架設SMTP郵件服務器,可以將該端口關閉。

          53端口:53端口為DNS(Domain Name Server,域名服務器)服務器所開放,主要用于域名解析,DNS服務在NT系統中使用的最為廣泛。

          端口說明:53端口為DNS(Domain Name Server,域名服務器)服務器所開放,主要用于域名解析,DNS服務在NT系統中使用的最為廣泛。通過DNS服務器可以實現域名與IP地址之間的轉換,只要記住域名就可以快速訪問網站。

          端口漏洞:如果開放DNS服務,黑客可以通過分析DNS服務器而直接獲取Web服務器等主機的IP地址,再利用53端口突破某些不穩定的防火墻,從而實施攻擊。近日,美國一家公司也公布了10個最易遭黑客攻擊的漏洞,其中第一位的就是DNS服務器的BIND漏洞。

          操作建議:如果當前的計算機不是用于提供域名解析服務,建議關閉該端口。

          67、68端口:67、68端口分別是為Bootp服務的Bootstrap Protocol Server(引導程序協議服務端)和Bootstrap Protocol Client(引導程序協議客戶端)開放的端口。

          端口說明:67、68端口分別是為Bootp服務的Bootstrap Protocol Server(引導程序協議服務端)和Bootstrap Protocol Client(引導程序協議客戶端)開放的端口。Bootp服務是一種產生于早期Unix的遠程啟動協議,我們現在經常用到的DHCP服務就是從Bootp服務擴展而來的。通過Bootp服務可以為局域網中的計算機動態分配IP地址,而不需要每個用戶去設置靜態IP地址。

          端口漏洞:如果開放Bootp服務,常常會被黑客利用分配的一個IP地址作為局部路由器通過“中間人”(man-in-middle)方式進行攻擊。

          操作建議:建議關閉該端口。


          69端口:TFTP是Cisco公司開發的一個簡單文件傳輸協議,類似于FTP。

          端口說明:69端口是為TFTP(Trival File Tranfer Protocol,次要文件傳輸協議)服務開放的,TFTP是Cisco公司開發的一個簡單文件傳輸協議,類似于FTP。不過與FTP相比,TFTP不具有復雜的交互存取接口和認證控制,該服務適用于不需要復雜交換環境的客戶端和服務器之間進行數據傳輸。

          端口漏洞:很多服務器和Bootp服務一起提供TFTP服務,主要用于從系統下載啟動代碼??墒?,因為TFTP服務可以在系統中寫入文件,而且黑客還可以利用TFTP的錯誤配置來從系統獲取任何文件。

          操作建議:建議關閉該端口。

          79端口:79端口是為Finger服務開放的,主要用于查詢遠程主機在線用戶、操作系統類型以及是否緩沖區溢出等用戶的詳細信息。

          端口說明:79端口是為Finger服務開放的,主要用于查詢遠程主機在線用戶、操作系統類型以及是否緩沖區溢出等用戶的詳細信息。比如要顯示遠程計算機www.abc.com上的user01用戶的信息,可以在命令行中鍵入“finger user01@www.abc.com”即可。

          端口漏洞:一般黑客要攻擊對方的計算機,都是通過相應的端口掃描工具來獲得相關信息,比如使用“流光”就可以利用79端口來掃描遠程計算機操作系統版本,獲得用戶信息,還能探測已知的緩沖區溢出錯誤。這樣,就容易遭遇到黑客的攻擊。而且,79端口還被Firehotcker木馬作為默認的端口。

          操作建議:建議關閉該端口。

          80端口:80端口是為HTTP(HyperText Transport Protocol,超文本傳輸協議)開放的,這是上網沖浪使用最多的協議,主要用于在WWW(World Wide Web,萬維網)服務上傳輸信息的協議。

          端口說明:80端口是為HTTP(HyperText Transport Protocol,超文本傳輸協議)開放的,這是上網沖浪使用最多的協議,主要用于在WWW(World Wide Web,萬維網)服務上傳輸信息的協議。我們可以通過HTTP地址加“:80”(即常說的“網址”)來訪問網站的,比如http://www.cce.com.cn:80,因為瀏覽網頁服務默認的端口號是80,所以只要輸入網址,不用輸入“:80”。

          端口漏洞:有些木馬程序可以利用80端口來攻擊計算機的,比如Executor、RingZero等。

          操作建議:為了能正常上網沖浪,我們必須開啟80端口。

          99端口:99端口是用于一個名為“Metagram Relay”(亞對策延時)的服務,該服務比較少見,一般是用不到的。

          端口說明:99端口是用于一個名為“Metagram Relay”(亞對策延時)的服務,該服務比較少見,一般是用不到的。

          端口漏洞:雖然“Metagram Relay”服務不常用,可是Hidden Port、NCx99等木馬程序會利用該端口,比如在Windows 2000中,NCx99可以把cmd.exe程序綁定到99端口,這樣用Telnet就可以連接到服務器,隨意添加用戶、更改權限。

          操作建議:建議關閉該端口。


          109、110端口:109端口是為POP2(Post Office Protocol Version 2,郵局協議2)服務開放的,110端口是為POP3(郵件協議3)服務開放的,POP2、POP3都是主要用于接收郵件的。

          端口說明:109端口是為POP2(Post Office Protocol Version 2,郵局協議2)服務開放的,110端口是為POP3(郵件協議3)服務開放的,POP2、POP3都是主要用于接收郵件的,目前POP3使用的比較多,許多服務器都同時支持POP2和POP3。客戶端可以使用POP3協議來訪問服務端的郵件服務,如今ISP的絕大多數郵件服務器都是使用該協議。在使用電子郵件客戶端程序的時候,會要求輸入POP3服務器地址,默認情況下使用的就是110端口。

          端口漏洞:POP2、POP3在提供郵件接收服務的同時,也出現了不少的漏洞。單單POP3服務在用戶名和密碼交換緩沖區溢出的漏洞就不少于20個,比如WebEasyMail POP3 Server合法用戶名信息泄露漏洞,通過該漏洞遠程攻擊者可以驗證用戶賬戶的存在。另外,110端口也被ProMail trojan等木馬程序所利用,通過110端口可以竊取POP賬號用戶名和密碼。

          操作建議:如果是執行郵件服務器,可以打開該端口。

          111端口:111端口是SUN公司的RPC(Remote Procedure Call,遠程過程調用)服務所開放的端口,主要用于分布式系統中不同計算機的內部進程通信,RPC在多種網絡服務中都是很重要的組件。

          端口說明:111端口是SUN公司的RPC(Remote Procedure Call,遠程過程調用)服務所開放的端口,主要用于分布式系統中不同計算機的內部進程通信,RPC在多種網絡服務中都是很重要的組件。常見的RPC服務有rpc.mountd、NFS、rpc.statd、rpc.csmd、rpc.ttybd、amd等等。在Microsoft的Windows中,同樣也有RPC服務。

          端口漏洞:SUN RPC有一個比較大漏洞,就是在多個RPC服務時xdr_array函數存在遠程緩沖溢出漏洞,通過該漏洞允許攻擊者傳遞超

          113端口:113端口主要用于Windows的“Authentication Service”(驗證服務)。

          端口說明:113端口主要用于Windows的“Authentication Service”(驗證服務),一般與網絡連接的計算機都運行該服務,主要用于驗證TCP連接的用戶,通過該服務可以獲得連接計算機的信息。在Windows 2000/2003 Server中,還有專門的IAS組件,通過該組件可以方便遠程訪問中進行身份驗證以及策略管理。

          端口漏洞:113端口雖然可以方便身份驗證,但是也常常被作為FTP、POP、SMTP、IMAP以及IRC等網絡服務的記錄器,這樣會被相應的木馬程序所利用,比如基于IRC聊天室控制的木馬。另外,113端口還是Invisible Identd Deamon、Kazimas等木馬默認開放的端口。

          操作建議:建議關閉該端口。


          119端口:119端口是為“Network News Transfer Protocol”(網絡新聞組傳輸協議,簡稱NNTP)開放的。

          端口說明:119端口是為“Network News Transfer Protocol”(網絡新聞組傳輸協議,簡稱NNTP)開放的,主要用于新聞組的傳輸,當查找USENET服務器的時候會使用該端口。

          端口漏洞:著名的Happy99蠕蟲病毒默認開放的就是119端口,如果中了該病毒會不斷發送電子郵件進行傳播,并造成網絡的堵塞。

          操作建議:如果是經常使用USENET新聞組,就要注意不定期關閉該端口。

          135端口:135端口主要用于使用RPC(Remote Procedure Call,遠程過程調用)協議并提供DCOM(分布式組件對象模型)服務。

          端口說明:135端口主要用于使用RPC(Remote Procedure Call,遠程過程調用)協議并提供DCOM(分布式組件對象模型)服務,通過RPC可以保證在一臺計算機上運行的程序可以順利地執行遠程計算機上的代碼;使用DCOM可以通過網絡直接進行通信,能夠跨包括HTTP協議在內的多種網絡傳輸。

          端口漏洞:相信去年很多Windows 2000和Windows XP用戶都中了“沖擊波”病毒,該病毒就是利用RPC漏洞來攻擊計算機的。RPC本身在處理通過TCP/IP的消息交換部分有一個漏洞,該漏洞是由于錯誤地處理格式不正確的消息造成的。該漏洞會影響到RPC與DCOM之間的一個接口,該接口偵聽的端口就是135。

          操作建議:為了避免“沖擊波”病毒的攻擊,建議關閉該端口。

          137端口:137端口主要用于“NetBIOS Name Service”(NetBIOS名稱服務)。

          端口說明:137端口主要用于“NetBIOS Name Service”(NetBIOS名稱服務),屬于UDP端口,使用者只需要向局域網或互聯網上的某臺計算機的137端口發送一個請求,就可以獲取該計算機的名稱、注冊用戶名,以及是否安裝主域控制器、IIS是否正在運行等信息。

          端口漏洞:因為是UDP端口,對于攻擊者來說,通過發送請求很容易就獲取目標計算機的相關信息,有些信息是直接可以被利用,并分析漏洞的,比如IIS服務。另外,通過捕獲正在利用137端口進行通信的信息包,還可能得到目標計算機的啟動和關閉的時間,這樣就可以利用專門的工具來攻擊。

          操作建議:建議關閉該端口。


          139端口:139端口是為“NetBIOS Session Service”提供的,主要用于提供Windows文件和打印機共享以及Unix中的Samba服務。

          端口說明:139端口是為“NetBIOS Session Service”提供的,主要用于提供Windows文件和打印機共享以及Unix中的Samba服務。在Windows中要在局域網中進行文件的共享,必須使用該服務。比如在Windows 98中,可以打開“控制面板”,雙擊“網絡”圖標,在“配置”選項卡中單擊“文件及打印共享”按鈕選中相應的設置就可以安裝啟用該服務;在Windows 2000/XP中,可以打開“控制面板”,雙擊“網絡連接”圖標,打開本地連接屬性;接著,在屬性窗口的“常規”選項卡中選擇“Internet協議(TCP/IP)”,單擊“屬性”按鈕;然后在打開的窗口中,單擊“高級”按鈕;在“高級TCP/IP設置”窗口中選擇“WINS”選項卡,在“NetBIOS設置”區域中啟用TCP/IP上的NetBIOS。

          端口漏洞:開啟139端口雖然可以提供共享服務,但是常常被攻擊者所利用進行攻擊,比如使用流光、SuperScan等端口掃描工具,可以掃描目標計算機的139端口,如果發現有漏洞,可以試圖獲取用戶名和密碼,這是非常危險的。

          操作建議:如果不需要提供文件和打印機共享,建議關閉該端口。

          143端口:143端口主要是用于“Internet Message Access Protocol”v2(Internet消息訪問協議,簡稱IMAP)。

          端口說明:143端口主要是用于“Internet Message Access Protocol”v2(Internet消息訪問協議,簡稱IMAP),和POP3一樣,是用于電子郵件的接收的協議。通過IMAP協議我們可以在不接收郵件的情況下,知道信件的內容,方便管理服務器中的電子郵件。不過,相對于POP3協議要負責一些。如今,大部分主流的電子郵件客戶端軟件都支持該協議。

          端口漏洞:同POP3協議的110端口一樣,IMAP使用的143端口也存在緩沖區溢出漏洞,通過該漏洞可以獲取用戶名和密碼。另外,還有一種名為“admv0rm”的Linux蠕蟲病毒會利用該端口進行繁殖。

          操作建議:如果不是使用IMAP服務器操作,應該將該端口關閉。

          161端口:161端口是用于“Simple Network Management Protocol”(簡單網絡管理協議,簡稱SNMP)。

          端口說明:161端口是用于“Simple Network Management Protocol”(簡單網絡管理協議,簡稱SNMP),該協議主要用于管理TCP/IP網絡中的網絡協議,在Windows中通過SNMP服務可以提供關于TCP/IP網絡上主機以及各種網絡設備的狀態信息。目前,幾乎所有的網絡設備廠商都實現對SNMP的支持。

          在Windows 2000/XP中要安裝SNMP服務,我們首先可以打開“Windows組件向導”,在“組件”中選擇“管理和監視工具”,單擊“詳細信息”按鈕就可以看到“簡單網絡管理協議(SNMP)”,選中該組件;然后,單擊“下一步”就可以進行安裝。

          端口漏洞:因為通過SNMP可以獲得網絡中各種設備的狀態信息,還能用于對網絡設備的控制,所以黑客可以通過SNMP漏洞來完全控制網絡。

          操作建議:建議關閉該端口。


          443端口:443端口即網頁瀏覽端口,主要是用于HTTPS服務,是提供加密和通過安全端口傳輸的另一種HTTP。

          端口說明:443端口即網頁瀏覽端口,主要是用于HTTPS服務,是提供加密和通過安全端口傳輸的另一種HTTP。在一些對安全性要求較高的網站,比如銀行、證券、購物等,都采用HTTPS服務,這樣在這些網站上的交換信息其他人都無法看到,保證了交易的安全性。網頁的地址以https://開始,而不是常見的http://。

          端口漏洞:HTTPS服務一般是通過SSL(安全套接字層)來保證安全性的,但是SSL漏洞可能會受到黑客的攻擊,比如可以黑掉在線銀行系統,盜取信用卡賬號等。

          操作建議:建議開啟該端口,用于安全性網頁的訪問。另外,為了防止黑客的攻擊,應該及時安裝微軟針對SSL漏洞發布的最新安全補丁。

          554端口:554端口默認情況下用于“Real Time Streaming Protocol”(實時流協議,簡稱RTSP)。

          端口說明:554端口默認情況下用于“Real Time Streaming Protocol”(實時流協議,簡稱RTSP),該協議是由RealNetworks和Netscape共同提出的,通過RTSP協議可以借助于Internet將流媒體文件傳送到RealPlayer中播放,并能有效地、最大限度地利用有限的網絡帶寬,傳輸的流媒體文件一般是Real服務器發布的,包括有.rm、.ram。如今,很多的下載軟件都支持RTSP協議,比如FlashGet、影音傳送帶等等。

          端口漏洞:目前,RTSP協議所發現的漏洞主要就是RealNetworks早期發布的Helix Universal Server存在緩沖區溢出漏洞,相對來說,使用的554端口是安全的。

          操作建議:為了能欣賞并下載到RTSP協議的流媒體文件,建議開啟554端口。

          1024端口:1024端口一般不固定分配給某個服務,在英文中的解釋是“Reserved”(保留)。

          端口說明:1024端口一般不固定分配給某個服務,在英文中的解釋是“Reserved”(保留)。之前,我們曾經提到過動態端口的范圍是從1024~65535,而1024正是動態端口的開始。該端口一般分配給第一個向系統發出申請的服務,在關閉服務的時候,就會釋放1024端口,等待其他服務的調用。

          端口漏洞:著名的YAI木馬病毒默認使用的就是1024端口,通過該木馬可以遠程控制目標計算機,獲取計算機的屏幕圖像、記錄鍵盤事件、獲取密碼等,后果是比較嚴重的。

          操作建議:一般的殺毒軟件都可以方便地進行YAI病毒的查殺,所以在確認無YAI病毒的情況下建議開啟該端口。


          posted @ 2011-11-01 11:12 abin 閱讀(328) | 評論 (0)編輯 收藏

               摘要: <servlet>     <description>This is the description of my J2EE component</description>     <display-name>This is the display name of my J2EE comp...  閱讀全文
          posted @ 2011-10-31 20:15 abin 閱讀(1164) | 評論 (0)編輯 收藏

          作為一個J2EE的開發者,我們基本上是開發基于WEB的應用系統。事實上,工作流,狀態管理以及驗證都是需要解決的重要功能。而HTTP協議的無狀態性決定了這些功能都不容易實現。SpringWEB框架就是來幫助我們解決這些問題的。使用Spring,我們可以讓WEB框架自動將傳遞進來的請求參數填充到模型對象中,同時提供驗證和錯誤處理。還可以管理用戶在WEB表單中創建的對象的狀態。在了解SpringMVC之前,我們先來復習下MVC.

          MVC從邏輯上把應用分為模型組件,視圖組件和控制器組件。其中控制器組件又可以細分為:前端控制器組件和后端控制器組件。

           

          我們來看一下MVC的基本工作流程:

           

          首先是客戶端(通常是瀏覽器)發出一個請求。第一個接受這個請求的組件一般是一個前端控制器。它將不同的請求交給不同的后端控制器來處理,而在后端控制器里面又可以調用相應的模型對象來處理具體的業務邏輯,最后再返回一個特定的視圖響應給客戶端。

           

          怎么理解MVC呢? 我們舉一個現實的例子,前段時間地震太可怕了,全國人民都在上下一心抗震救災。我們敬愛的溫總理給武警司令下命令讓他完成抗震救災的艱巨任務,于是武警司 令就根據各地情況派遣不同類型的特種兵到不同的地區去,然后特種兵使用大大小小的工具完成了任務,最后上交給司令一份統計圖表,司令再上交給溫總理。我們 就來分析一下,這符不符合MVC的設計模式。這里呢,溫總理就是客戶端,武警司令就是前端控制器,特種兵就是后端控制器,特種兵所使用的工具就是模型,最后上交的統計圖表就是視圖。

           

          現在大家應該可以理解MVC的設計思想了。拿我們比較熟悉的struts框架來說,前端控制器就是ActionServlet,后端控制器就是Action.請求的URL和后端控制器的映射關系在struts-config.xml上的<action-mappings>里面配置,模型對象就是我們平常寫的DAO/DTO,返回的視圖類型一般就是jsp了。

           

          那么,在spring MVC中又是怎樣的呢?,我們先按上面對號入座地說一下。第一個接受這個請求的前端控制器叫DispatcherServlet,后端控制器叫Controller。負責處理請求URL和后端控制器映射的叫HandMapping,它有多種類型,比較靈活,也是在一個xml文件上進行配置。負責業務邏輯處理的模型對象一般也是我們平常寫的DAO/DTO組件。只是它最后的返回更靈活,Controller返回一個ModelAndView對象給DispatcherServletModelAndView可以攜帶一個視圖對象,也可以攜帶一個視圖對象的邏輯名。如果攜帶的是一個視圖對象的邏輯名,那DispatcherServlet需要一個ViewResolver來查找用于渲染回應的視圖對象。最后,DispatcherServlet將請求分派給ModelAndView對象指定的視圖對象。視圖對象負責渲染返回給客戶的回應。

           

                 我們學習知識,一樣要注意運用類比遷移的方法。有人說,我學會了struts,但學不會springMVC。這是說不過去的。因為二者的思想完全一致。所以,我們只需要學習它們不一樣的地方就可以啦。好,我們現在先跑一個最簡單的例子,讓大家對構建SpringMVC的基本步驟有個直觀的認識。大家要邊跑邊跟struts做比較。

          (1)建立動態web工程,導入springjar包。

           

          (2)配置DispatcherServlet

           

          DispatcherServletSpringMVC的核心,將下面Servlet的注冊信息登記在web.xml中。一定要記?。?/span>Servlet跟伴侶一樣,要結婚,先得注冊登記!

          <servlet>

            <servlet-name>test</servlet-name>  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

            <load-on-startup>1</load-on-startup>

           </servlet>

           

           <servlet-mapping>

            <servlet-name>test</servlet-name>

            <url-pattern>*.do</url-pattern>

           </servlet-mapping>

           

          (3)編寫Controller,做核心配置文件,并配置urlController的映射

           

          package com.wepull.test;

           

          import javax.servlet.http.HttpServletRequest;

          import javax.servlet.http.HttpServletResponse;

           

          import org.springframework.web.servlet.ModelAndView;

          import org.springframework.web.servlet.mvc.Controller;

           

          public classHelloController implements Controller{

              public ModelAndView handleRequest(HttpServletRequest request,

                        HttpServletResponse response) throws Exception {

                       request.setAttribute("hello""welcome to spring!");

                       return new ModelAndView("welcome");

                      }

          }

          我們知道Struts有個XML格式的核心配置文件,springMVC當然也有,在WEB-INF下新建一XML文件:test-servlet.xml.注意,這里的test取決于servlet的名字.DispatcherServlet載入后,它將試圖從這個文件中載入應用上下文。

          <?xml version="1.0" encoding="UTF-8"?>

          <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

          <beans>

              <!--缺省映射處理器,不需要明確聲明,但聲明后就非常清楚使用的是哪個映射處理器  -->   <bean id="beanNameUrlMapping"

              class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">

              </bean>

              <!-- 這里的name屬性有兩個職責,既定義Bean的名字,也定義需要這個控制器處理的URL樣式 -->

              <bean name="/hello.do"

                 class="com.wepull.test.HelloController">

              </bean>

          </beans>

          上面可能有人奇怪,為什么不用id屬性,而設置name屬性。這里是因為URL中含有XML id屬性非法字符——特別是斜杠(/;

           

          (4)配置一個視圖解析器將控制器與JSP結合起來。

           

          將解析器的配置片段加到上面的test-servlet.xml中。

          <bean id="viewResolver"

              class="org.springframework.web.servlet.view.InternalResourceViewResolver">

                 <property name="prefix" value="/WEB-INF/jsp/" />

                 <property name="suffix" value=".jsp" />

          </bean>

          InternalResourceViewResolverModelAndView返回的視圖名前加上prefix屬性配置的前綴,再在最后加上suffix屬性配置的后綴。由于HelloController返回的ModelAndView中視圖名為welcome,所以InternalResourceViewResolver將在/WEB-INF/jsp/welcome.jsp處查找視圖。

           

          (5)編寫呈現給用戶的jsp文件。

           

          /WEB-INF/jsp/welcome.jsp

          <%@ page contentType="text/html; charset=UTF-8"%>

          <%@ page isELIgnored="false" %>

          <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

          <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

          <html xmlns="http://www.w3.org/1999/xhtml">

           <head>

            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

            <title>Hello World!</title>

           </head>

           <body>

            <h2>

             ${hello}

            </h2>

           </body>

          </html>

           

          完成后啟動服務器,在瀏覽器地址欄上輸入http://locahost:8080/projectName/hello.do       就可以訪問了。

                 對照一下,我們發現SpringMVCStruts大同小異。只是有兩處映射,SpringMVC做的相對靈活。哪兩處呢?

          (1) url和動作(后端控制器)的映射。

          springMVC里有個映射處理器(HandlerMapping)的概念。它實際上是一個處理器映射Bean,用來將一個控制器指定到一個URL上。Spring提供了三種有用的HandlerMapping的實現:

          ——BeanNameUrlHandlerMapping

                 根據控制器的名字將控制器映射到URL

          ——SimpleUrlHandlerMapping

                 用上下文配置文件中定義的屬性集合將控制器映射到URL

          ——CommonsPathMapHandlerMapping

                 使用控制器代碼中的元數據將控制器映射到URL   

          (2) 邏輯視圖名和視圖對象的映射。

          springMVC里還有個視圖解析器(ViewResolver)的概念。它決定了ModelAndView對象的邏輯視圖名如何解析成一個用于將結果渲染給用戶的視圖Bean..Spring有四種ViewResolver實現:

          ——InternalResourceViewResolver

                 將邏輯視圖名解析成一個用模板文件(JSPVelocity模板)渲染的視圖對象

          ——BeanNameViewResolver

                 將邏輯視圖名解析成一個DispatcherServlet應用上下文中的視圖Bean

          ——ResourceBundleViewResolver

                 將邏輯視圖名解析成一個ResourceBundler中的視圖對象

          —— XmlViewResolver

                 從一個XML文件中解析視圖Bean,這個文件是從DispatcherServlet應用上下文中分離出來的。

                 好啦,今天就算是SpringMVC的一個入門。建議大家將StrutsSpringMVC對照著學習,那樣效果會更好。與人分享,集思廣益。希望大家都能夠學習快樂,工作順心。下次再見。

          出處:http://blog.csdn.net/lenotang/article/details/2562348

          posted @ 2011-10-23 22:08 abin 閱讀(1069) | 評論 (1)編輯 收藏

          //Java接收郵件主程序:

          import java.io.BufferedInputStream;
          import java.io.BufferedOutputStream;
          import java.io.File;
          import java.io.FileOutputStream;
          import java.io.InputStream;
          import java.text.SimpleDateFormat;
          import java.util.ArrayList;
          import java.util.Date;
          import java.util.List;
          import java.util.Properties;

          import javax.mail.BodyPart;
          import javax.mail.Flags;
          import javax.mail.Folder;
          import javax.mail.Message;
          import javax.mail.MessagingException;
          import javax.mail.Multipart;
          import javax.mail.Part;
          import javax.mail.Session;
          import javax.mail.Store;
          import javax.mail.internet.InternetAddress;
          import javax.mail.internet.MimeMessage;
          import javax.mail.internet.MimeUtility;

          /**
           * @author Administrator
           *
           */
          public class PraseMimeMessage {
              private MimeMessage mimeMessage = null;

              private String saveAttachPath = "d:\\";// 附件下載后的存放目錄

              private StringBuffer bodytext = new StringBuffer();

              // 存放郵件內容的StringBuffer對象
              private String dateformat = "yy-MM-dd HH:mm";// 默認的日前顯示格式

              /**
               * 構造函數,初始化一個MimeMessage對象
               */
              public PraseMimeMessage() {
              }

              public PraseMimeMessage(MimeMessage mimeMessage) {
                  this.mimeMessage = mimeMessage;
          //        System.out.println("create a PraseMimeMessage object........");
              }

              public void setMimeMessage(MimeMessage mimeMessage) {
                  this.mimeMessage = mimeMessage;
              }

              /**
               *
               * 獲取發件人的姓名和密碼
               *
               * @return
               */
              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 java.util.Date getSentDate() throws Exception {
                  Date sentdate = mimeMessage.getSentDate();
                  SimpleDateFormat format = new SimpleDateFormat(dateformat);
                  return sentdate;
              }

              /**
               * 獲取郵件正文
               *
               * @return
               *
               */

              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;
              }
              //base64解碼
              private static String base64Decoder(String s) throws Exception {
                  sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
                  byte[] b = decoder.decodeBuffer(s);
                  return (new String(b));
              }

              /*
               * 保存附件
               *
               */
              public String saveAttachMent(Part part) throws Exception {
                  String fileName = "";
                  StringBuffer stb=new StringBuffer();
                  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();
                               /*System.out.println(fileName);
                               fileName=fileName.substring(fileName.indexOf("=?GBK?B?"));
                               System.out.println(fileName);
                               fileName=fileName.substring(0, fileName.length()-2);
                               System.out.println(fileName);*/
          //                     .substring(fileName.lastIndexOf("=?GBK?B?"), fileName.indexOf("?="));
                               String s = fileName.substring(8, fileName.indexOf("?="));;
                               fileName = base64Decoder(s);
                               stb.append(fileName);
                                  stb.append(",");
                              if (fileName.toLowerCase().indexOf("gb2312") != -1) {
                                  fileName = MimeUtility.decodeText(fileName);
                                  stb.append(fileName);
                                  stb.append(",");
                              }
                              // saveFile(fileName,mpart.getInputStream());
                              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);
                                  stb.append(fileName);
                                  stb.append(",");
                                  
                                  saveFile(fileName, mpart.getInputStream());
                              }
                          }
                      }
                  } else if (part.isMimeType("message/rfc822")) {
                      saveAttachMent((Part) part.getContent());
                  }
                  return stb.toString();
              }

              /**
               * 【設置附件存放路徑】
               */

              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());

                  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類測試
               */

              public static void main(String args[]) throws Exception {
                  String host = "POP3.163.com";// 【POP3.163.com】
                  String username = "liposter";// 【yuxia2217】
                  String password = "liisposter";// 【........】
                  Properties props = new Properties();
                  Session session = Session.getDefaultInstance(props, null);
                  Store store = session.getStore("pop3");
                  store.connect(host, username, password);
                  Folder folder = store.getFolder("INBOX");
                  folder.open(Folder.READ_ONLY);
                  Message message[] = folder.getMessages();
                  System.out.println("Messages's length: " + message.length);
                  PraseMimeMessage pmm = null;
                  for (int i = 0; i < message.length; i++) {
                      pmm = new PraseMimeMessage((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("D:\\image");
                      pmm.saveAttachMent((Part) message[i]);
                      

                  }
              }
              public List<MailInfo> receive(MailInfo mailInfo)throws Exception{
                  List<MailInfo> list=new ArrayList<MailInfo>();
                  Properties props = new Properties();
                  Session session = Session.getDefaultInstance(props, null);
                  Store store = session.getStore("pop3");
                  store.connect(mailInfo.getHost(), mailInfo.getUsername(), mailInfo.getPassword());
                  Folder folder = store.getFolder("INBOX");
                  folder.open(Folder.READ_ONLY);
                  Message message[] = folder.getMessages();
              //    System.out.println("Messages's length: " + message.length);
                  PraseMimeMessage pmm = null;
                  for (int i = 0; i < message.length; i++) {
                      MailInfo mail=new MailInfo();
                      mail.setMailnumber(message.length);
                      pmm = new PraseMimeMessage((MimeMessage) message[i]);
          //            System.out
          //                    .println("Message " + i + " subject: " + pmm.getSubject());
                      mail.setSubject(message[i].getSubject());
          //            System.out.println("Message " + i + " sentdate: "
          //                    + pmm.getSentDate());
                      mail.setSentdate(pmm.getSentDate());
          //            System.out.println("Message " + i + " replysign: "
          //                    + pmm.getReplySign());
                      mail.setReplysign(pmm.getReplySign());
          //            System.out.println("Message 新的" + i + " hasRead: " + pmm.isNew());
          //            mail.setRead(pmm.isNew());
          //            System.out.println("Message 附件" + i + "  containAttachment: "
          //                    + pmm.isContainAttach((Part) message[i]));
                      mail.setExistsFile(pmm.isContainAttach((Part) message[i]));
          //            System.out.println("Message " + i + " form: " + pmm.getFrom());
                      mail.setFromAddress(pmm.getFrom().substring(1, pmm.getFrom().length()).replaceAll(">", ""));
          //            System.out.println("Message " + i + " to: "
          //                    + pmm.getMailAddress("to"));
                      mail.setToAddress(pmm.getMailAddress("to").substring(1, pmm.getMailAddress("to").length()).replaceAll(">", ""));
          //            System.out.println("Message " + i + " cc: "
          //                    + pmm.getMailAddress("cc"));
          //            mail.setMailauthor(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());
                      mail.setMessageid(pmm.getMessageId());
                      pmm.getMailContent((Part) message[i]);
          //            System.out.println("Message 正文" + i + " bodycontent: \r\n"
          //                    + pmm.getBodyText());
                      mail.setContent(pmm.getBodyText());
                      pmm.setAttachPath(mailInfo.getFilepath()[0]);
                      String fileName=pmm.saveAttachMent((Part) message[i]);
                      String[] file=new String[]{};
                      file=fileName.split(",");
                      String[] receivepath=new String[3];
                      for(int j=0;j<file.length;j++){
                          receivepath[j]=mailInfo.getFilepath()[0]+"\\"+file[j];
                      }
                      mail.setReceivepath(receivepath);
                      list.add(mail);
              }
                  return list;
          }
          }



            



          //實體類
          /**
           * 發送郵件的基本信息
           * @author dell
           *
           */
          public class MailInfo implements java.io.Serializable{

              private String host;//發送郵件的主機號
              private String port;//發送郵件的端口號
              private String fromAddress;//發送郵件地址
              private String toAddress;//接收郵件地址
              private String username;//發送郵件用戶的用戶名
              private String password;//發送郵件用戶的密碼
              private String validate;//是否需要身份的驗證:ture認證,false不認證信息
              private String subject;//郵件主題
              private String content;//郵件的內容,分為文本,超文本,html等形式
              private String[] filepath;//發送郵件的附件的位置
              private String[] sendAddress;//接收郵件地址
              private String filename;//發送郵件的附件顯示的名稱
              private String[] receivepath;//接收郵件的時候附件保存的路徑
              private java.util.Date sentdate;
              private float filesize;
              private java.util.Date receivedate;
              private String mailauthor;//郵件作者
              private boolean read;//是否讀過,true讀過,false沒有閱讀過
              private boolean ExistsFile;//是否有附件true有,false沒有
              private boolean replysign;//是否有回執
              private String messageid;//消息ID
              private int mailnumber;//郵件數目,一個用戶的總郵件數
              
              
              public String[] getSendAddress() {
                  return sendAddress;
              }
              public void setSendAddress(String[] sendAddress) {
                  this.sendAddress = sendAddress;
              }
              public int getMailnumber() {
                  return mailnumber;
              }
              public void setMailnumber(int mailnumber) {
                  this.mailnumber = mailnumber;
              }
              public String getMessageid() {
                  return messageid;
              }
              public void setMessageid(String messageid) {
                  this.messageid = messageid;
              }
              public boolean isExistsFile() {
                  return ExistsFile;
              }
              public boolean isRead() {
                  return read;
              }
              public void setExistsFile(boolean existsFile) {
                  ExistsFile = existsFile;
              }
              public void setRead(boolean read) {
                  this.read = read;
              }
              public boolean isReplysign() {
                  return replysign;
              }
              public void setReplysign(boolean replysign) {
                  this.replysign = replysign;
              }
              public String getMailauthor() {
                  return mailauthor;
              }
              public void setMailauthor(String mailauthor) {
                  this.mailauthor = mailauthor;
              }
              public java.util.Date getReceivedate() {
                  return receivedate;
              }
              public void setReceivedate(java.util.Date receivedate) {
                  this.receivedate = receivedate;
              }

              public java.util.Date getSentdate() {
                  return sentdate;
              }
              public void setSentdate(java.util.Date sentdate) {
                  this.sentdate = sentdate;
              }
              
              public String[] getFilepath() {
                  return filepath;
              }
              public void setFilepath(String[] filepath) {
                  this.filepath = filepath;
              }
              public String getContent() {
                  return content;
              }
              public String getFilename() {
                  return filename;
              }
              public String getFromAddress() {
                  return fromAddress;
              }
              public String getHost() {
                  return host;
              }
              public String getPassword() {
                  return password;
              }
              public String getPort() {
                  return port;
              }
              public String getSubject() {
                  return subject;
              }
              public String getToAddress() {
                  return toAddress;
              }
              public String getUsername() {
                  return username;
              }
              public void setContent(String content) {
                  this.content = content;
              }
              public void setFilename(String filename) {
                  this.filename = filename;
              }
              public void setFromAddress(String fromAddress) {
                  this.fromAddress = fromAddress;
              }
              public void setHost(String host) {
                  this.host = host;
              }
              public void setPassword(String password) {
                  this.password = password;
              }
              public void setPort(String port) {
                  this.port = port;
              }
              public void setSubject(String subject) {
                  this.subject = subject;
              }
              public void setToAddress(String toAddress) {
                  this.toAddress = toAddress;
              }
              public void setUsername(String username) {
                  this.username = username;
              }
              public String getValidate() {
                  return validate;
              }
              public void setValidate(String validate) {
                  this.validate = validate;
              }
              public String[] getReceivepath() {
                  return receivepath;
              }
              public void setReceivepath(String[] receivepath) {
                  this.receivepath = receivepath;
              }
              
              
              
              
              
          }






          //測試代碼:

          import java.util.List;

          import org.junit.After;
          import org.junit.Before;
          import org.junit.Test;
          public class ReceiveTest{
              @Before
              public void setUp() throws Exception {
              }

              @After
              public void tearDown() throws Exception {
              }
              @Test
              public void ReceiveMailTest()throws Exception{
                  MailInfo mailInfo=new MailInfo();
                  mailInfo.setHost("pop.163.com");
                  mailInfo.setUsername("liposter");
                  mailInfo.setPassword("********");
                  String[] fdess=new String[]{"D:\\image"};
                  mailInfo.setFilepath(fdess);
                  List<MailInfo> list=new PraseMimeMessage().receive(mailInfo);
                  for(int i=0;i<list.size();i++){
                      System.out.println("Mailnumber="+list.get(i).getMailnumber());
                      System.out.println("Subject="+list.get(i).getSubject());
                      System.out.println("Content="+list.get(i).getContent());
                      System.out.println("Filename="+list.get(i).getFilename());
                      System.out.println("SentDate="+list.get(i).getSentdate());
                      System.out.println("Messageid="+list.get(i).getMessageid());
                      System.out.println("ExistsFile="+list.get(i).isExistsFile());
                      System.out.println("Read="+list.get(i).isRead());
                      System.out.println("Replysign="+list.get(i).isReplysign());
                      for(int j=0;j<list.get(i).getReceivepath().length;j++){
                          System.out.println("第"+j+1+"個附件的Receivepath="+list.get(i).getReceivepath()[j]);
                      }
                      System.out.println("FromAddress="+list.get(i).getFromAddress());
                      System.out.println("ToAddress="+list.get(i).getToAddress());
                  }
              }

          }
          posted @ 2011-10-19 00:17 abin 閱讀(2900) | 評論 (1)編輯 收藏

          //實體類:
          /**
           * 發送郵件的基本信息
           * @author dell
           *
           */
          public class MailInfo implements java.io.Serializable{

              private String host;//發送郵件的主機號
              private String port;//發送郵件的端口號
              private String fromAddress;//發送郵件地址
              private String toAddress;//接收郵件地址
              private String username;//發送郵件用戶的用戶名
              private String password;//發送郵件用戶的密碼
              private String validate;//是否需要身份的驗證:ture認證,false不認證信息
              private String subject;//郵件主題
              private String content;//郵件的內容,分為文本,超文本,html等形式
              private String[] filepath;//發送郵件的附件的位置
              private String[] sendAddress;
              private String filename;//發送郵件的附件顯示的名稱
              private String receivepath;//接收郵件的時候附件保存的路徑
              private java.util.Date sentdate;
              private float filesize;
              private java.util.Date receivedate;
              private String mailauthor;//郵件作者
              private boolean read;//是否讀過,true讀過,false沒有閱讀過
              private boolean ExistsFile;//是否有附件true有,false沒有
              private boolean replysign;//是否有回執
              private String messageid;//消息ID
              private int mailnumber;//郵件數目,一個用戶的總郵件數
              
              
              public String[] getSendAddress() {
                  return sendAddress;
              }
              public void setSendAddress(String[] sendAddress) {
                  this.sendAddress = sendAddress;
              }
              public int getMailnumber() {
                  return mailnumber;
              }
              public void setMailnumber(int mailnumber) {
                  this.mailnumber = mailnumber;
              }
              public String getMessageid() {
                  return messageid;
              }
              public void setMessageid(String messageid) {
                  this.messageid = messageid;
              }
              public boolean isExistsFile() {
                  return ExistsFile;
              }
              public boolean isRead() {
                  return read;
              }
              public void setExistsFile(boolean existsFile) {
                  ExistsFile = existsFile;
              }
              public void setRead(boolean read) {
                  this.read = read;
              }
              public boolean isReplysign() {
                  return replysign;
              }
              public void setReplysign(boolean replysign) {
                  this.replysign = replysign;
              }
              public String getMailauthor() {
                  return mailauthor;
              }
              public void setMailauthor(String mailauthor) {
                  this.mailauthor = mailauthor;
              }
              public java.util.Date getReceivedate() {
                  return receivedate;
              }
              public void setReceivedate(java.util.Date receivedate) {
                  this.receivedate = receivedate;
              }

              public java.util.Date getSentdate() {
                  return sentdate;
              }
              public void setSentdate(java.util.Date sentdate) {
                  this.sentdate = sentdate;
              }
              
              public String[] getFilepath() {
                  return filepath;
              }
              public void setFilepath(String[] filepath) {
                  this.filepath = filepath;
              }
              public String getContent() {
                  return content;
              }
              public String getFilename() {
                  return filename;
              }
              public String getFromAddress() {
                  return fromAddress;
              }
              public String getHost() {
                  return host;
              }
              public String getPassword() {
                  return password;
              }
              public String getPort() {
                  return port;
              }
              public String getSubject() {
                  return subject;
              }
              public String getToAddress() {
                  return toAddress;
              }
              public String getUsername() {
                  return username;
              }
              public void setContent(String content) {
                  this.content = content;
              }
              public void setFilename(String filename) {
                  this.filename = filename;
              }
              public void setFromAddress(String fromAddress) {
                  this.fromAddress = fromAddress;
              }
              public void setHost(String host) {
                  this.host = host;
              }
              public void setPassword(String password) {
                  this.password = password;
              }
              public void setPort(String port) {
                  this.port = port;
              }
              public void setSubject(String subject) {
                  this.subject = subject;
              }
              public void setToAddress(String toAddress) {
                  this.toAddress = toAddress;
              }
              public void setUsername(String username) {
                  this.username = username;
              }
              public String getValidate() {
                  return validate;
              }
              public void setValidate(String validate) {
                  this.validate = validate;
              }
              public String getReceivepath() {
                  return receivepath;
              }
              public void setReceivepath(String receivepath) {
                  this.receivepath = receivepath;
              }
          }




          //發送郵件程序

          import java.util.Properties;

          import javax.activation.DataHandler;
          import javax.activation.DataSource;
          import javax.activation.FileDataSource;
          import javax.mail.BodyPart;
          import javax.mail.Message;
          import javax.mail.Multipart;
          import javax.mail.Session;
          import javax.mail.Transport;
          import javax.mail.internet.InternetAddress;
          import javax.mail.internet.MimeBodyPart;
          import javax.mail.internet.MimeMessage;
          import javax.mail.internet.MimeMultipart;
          import javax.mail.internet.MimeUtility;

          public class SendMail {
              
              public boolean Send(MailInfo mailInfo)throws Exception{
                  Properties props=new Properties();
                  //設置發送郵件的郵件服務器的屬性(這里使用網易的smtp服務器)
                  props.put("mail.smtp.host", mailInfo.getHost());
                  //需要經過授權,也就是有戶名和密碼的校驗,這樣才能通過驗證(一定要有這一條)
                  props.put("mail.smtp.auth", mailInfo.getValidate());
                  Session session=Session.getDefaultInstance(props);// 用剛剛設置好的props對象構建一個session
          //        session.setDebug(true);
                  MimeMessage message=new MimeMessage(session);
                  try{
                      message.setFrom(new InternetAddress(mailInfo.getFromAddress()));
                      InternetAddress[] sendTo = new InternetAddress[mailInfo.getSendAddress().length];
                      for(int i=0;i<mailInfo.getSendAddress().length;i++){
                          sendTo[i]=new InternetAddress(mailInfo.getSendAddress()[i]);
                      }
          //            message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailInfo.getToAddress()));
                      message.setRecipients(Message.RecipientType.TO, sendTo);
                      message.setSubject(mailInfo.getSubject());
                      message.setSentDate(mailInfo.getSentdate());
                      //向multipart對象中添加郵件的各個部分內容,包括文本內容和附件
                      Multipart multipart=new MimeMultipart();
                      BodyPart contentPart=new MimeBodyPart();
                      contentPart.setText(mailInfo.getContent());
                      multipart.addBodyPart(contentPart);
                      //添加附件
                      for(int i=0;i<mailInfo.getFilepath().length;i++){
                          BodyPart messageBodyPart=new MimeBodyPart();
                          String fpath=mailInfo.getFilepath()[i].split(",")[0];
                          DataSource source=new FileDataSource(fpath);
                          messageBodyPart.setDataHandler(new DataHandler(source));
                          sun.misc.BASE64Encoder enc=new sun.misc.BASE64Encoder();
                          String lname=fpath.substring(fpath.lastIndexOf("."), fpath.length());
                          String fname=String.valueOf(System.currentTimeMillis())+lname;
                          messageBodyPart.setFileName("=?GBK?B?"+enc.encode(fname.getBytes())+"?=");
                          multipart.addBodyPart(messageBodyPart);
                      }
                      
                      
                      message.setContent(multipart);//text/plain表示純文本內容
                      message.saveChanges();
                      Transport transport=session.getTransport("smtp");
                      transport.connect(mailInfo.getHost(),mailInfo.getUsername(),mailInfo.getPassword());
                      transport.sendMessage(message,message.getAllRecipients());
                      transport.close();
                      return true;
                  }catch(Exception e){
                      e.printStackTrace();
                  }
                  
                  return false;
              }
          }





          //測試代碼:

          import org.junit.After;
          import org.junit.Before;
          import org.junit.Test;

          public class SendTest {
              @Test
              public void mailTest(){
                  SendMail mail=new SendMail();
                  MailInfo mailInfo=new MailInfo();
                  mailInfo.setContent("郵件內容44444444444444444444");
                  String[] filepath=new String[]{"D:\\1317742305879.csv","D:\\zpssoa.log","E:\\Emotion\\Photo\\好寂寞好空虛.gif"};
                  mailInfo.setFilepath(filepath);
          //        mailInfo.setFilename("希望"+fname);
                  mailInfo.setFromAddress("leeposter@126.com");
                  mailInfo.setHost("smtp.126.com");
                  mailInfo.setSubject("郵件主題444444444444444444444");
          //        mailInfo.setToAddress("liposter@163.com");
                  String[] destination=new String[]{"liposter@163.com","lposter@163.com","liposter@126.com"};
                  mailInfo.setSendAddress(destination);
                  mailInfo.setUsername("leeposter");
                  mailInfo.setValidate("true");
                  mailInfo.setPassword("****");
                  try{
                      boolean flag=mail.Send(mailInfo);
                      if(flag==true){
                          System.out.println("發送成功");
                      }else{
                          System.out.println("發送失敗");
                      }
                  }catch(Exception e){
                      e.printStackTrace();
                  }
              }
          }
          posted @ 2011-10-18 23:28 abin 閱讀(1392) | 評論 (0)編輯 收藏

          郵件發送和接收已經全部實現,大家在轉發市請注明出處(我這也是參考了N多大牛的作品):


          //附件接收實現代碼:

          import java.io.BufferedInputStream;
          import java.io.BufferedOutputStream;
          import java.io.File;
          import java.io.FileOutputStream;
          import java.io.InputStream;
          import java.text.SimpleDateFormat;
          import java.util.ArrayList;
          import java.util.Date;
          import java.util.List;
          import java.util.Properties;

          import javax.mail.BodyPart;
          import javax.mail.Flags;
          import javax.mail.Folder;
          import javax.mail.Message;
          import javax.mail.MessagingException;
          import javax.mail.Multipart;
          import javax.mail.Part;
          import javax.mail.Session;
          import javax.mail.Store;
          import javax.mail.internet.InternetAddress;
          import javax.mail.internet.MimeMessage;
          import javax.mail.internet.MimeUtility;

          /**
           * @author Administrator
           *
           */
          public class PraseMimeMessage {
              private MimeMessage mimeMessage = null;

              private String saveAttachPath = "d:\\";// 附件下載后的存放目錄

              private StringBuffer bodytext = new StringBuffer();

              // 存放郵件內容的StringBuffer對象
              private String dateformat = "yy-MM-dd HH:mm";// 默認的日前顯示格式

              /**
               * 構造函數,初始化一個MimeMessage對象
               */
              public PraseMimeMessage() {
              }

              public PraseMimeMessage(MimeMessage mimeMessage) {
                  this.mimeMessage = mimeMessage;
          //        System.out.println("create a PraseMimeMessage object........");
              }

              public void setMimeMessage(MimeMessage mimeMessage) {
                  this.mimeMessage = mimeMessage;
              }

              /**
               *
               * 獲取發件人的姓名和密碼
               *
               * @return
               */
              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 java.util.Date getSentDate() throws Exception {
                  Date sentdate = mimeMessage.getSentDate();
                  SimpleDateFormat format = new SimpleDateFormat(dateformat);
                  return sentdate;
              }

              /**
               * 獲取郵件正文
               *
               * @return
               *
               */

              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;
              }
              //base64解碼
              private static String base64Decoder(String s) throws Exception {
                  sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
                  byte[] b = decoder.decodeBuffer(s);
                  return (new String(b));
              }

              /*
               * 保存附件
               *
               */
              public String 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();
                               /*System.out.println(fileName);
                               fileName=fileName.substring(fileName.indexOf("=?GBK?B?"));
                               System.out.println(fileName);
                               fileName=fileName.substring(0, fileName.length()-2);
                               System.out.println(fileName);*/
          //                     .substring(fileName.lastIndexOf("=?GBK?B?"), fileName.indexOf("?="));
                               String s = fileName.substring(8, fileName.indexOf("?="));;
                               fileName = base64Decoder(s);
                              if (fileName.toLowerCase().indexOf("gb2312") != -1) {
                                  fileName = MimeUtility.decodeText(fileName);
                              }
                              // saveFile(fileName,mpart.getInputStream());
                              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());
                  }
                  return fileName;
              }

              /**
               * 【設置附件存放路徑】
               */

              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());

                  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類測試
               */

              public static void main(String args[]) throws Exception {
                  String host = "POP3.163.com";// 【POP3.163.com】
                  String username = "li";// 【yuxia2217】
                  String password = "***";// 【........】
                  Properties props = new Properties();
                  Session session = Session.getDefaultInstance(props, null);
                  Store store = session.getStore("pop3");
                  store.connect(host, username, password);
                  Folder folder = store.getFolder("INBOX");
                  folder.open(Folder.READ_ONLY);
                  Message message[] = folder.getMessages();
                  System.out.println("Messages's length: " + message.length);
                  PraseMimeMessage pmm = null;
                  for (int i = 0; i < message.length; i++) {
                      pmm = new PraseMimeMessage((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("D:\\image");
                      pmm.saveAttachMent((Part) message[i]);
                      

                  }
              }
              public List<MailInfo> receive(MailInfo mailInfo)throws Exception{
                  List<MailInfo> list=new ArrayList<MailInfo>();
                  Properties props = new Properties();
                  Session session = Session.getDefaultInstance(props, null);
                  Store store = session.getStore("pop3");
                  store.connect(mailInfo.getHost(), mailInfo.getUsername(), mailInfo.getPassword());
                  Folder folder = store.getFolder("INBOX");
                  folder.open(Folder.READ_ONLY);
                  Message message[] = folder.getMessages();
              //    System.out.println("Messages's length: " + message.length);
                  PraseMimeMessage pmm = null;
                  for (int i = 0; i < message.length; i++) {
                      MailInfo mail=new MailInfo();
                      mail.setMailnumber(message.length);
                      pmm = new PraseMimeMessage((MimeMessage) message[i]);
          //            System.out
          //                    .println("Message " + i + " subject: " + pmm.getSubject());
                      mail.setSubject(message[i].getSubject());
          //            System.out.println("Message " + i + " sentdate: "
          //                    + pmm.getSentDate());
                      mail.setSentdate(pmm.getSentDate());
          //            System.out.println("Message " + i + " replysign: "
          //                    + pmm.getReplySign());
                      mail.setReplysign(pmm.getReplySign());
          //            System.out.println("Message 新的" + i + " hasRead: " + pmm.isNew());
          //            mail.setRead(pmm.isNew());
          //            System.out.println("Message 附件" + i + "  containAttachment: "
          //                    + pmm.isContainAttach((Part) message[i]));
                      mail.setExistsFile(pmm.isContainAttach((Part) message[i]));
          //            System.out.println("Message " + i + " form: " + pmm.getFrom());
                      mail.setFromAddress(pmm.getFrom().substring(1, pmm.getFrom().length()).replaceAll(">", ""));
          //            System.out.println("Message " + i + " to: "
          //                    + pmm.getMailAddress("to"));
                      mail.setToAddress(pmm.getMailAddress("to").substring(1, pmm.getMailAddress("to").length()).replaceAll(">", ""));
          //            System.out.println("Message " + i + " cc: "
          //                    + pmm.getMailAddress("cc"));
          //            mail.setMailauthor(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());
                      mail.setMessageid(pmm.getMessageId());
                      pmm.getMailContent((Part) message[i]);
          //            System.out.println("Message 正文" + i + " bodycontent: \r\n"
          //                    + pmm.getBodyText());
                      mail.setContent(pmm.getBodyText());
                      pmm.setAttachPath(mailInfo.getFilepath());
                      String fileName=pmm.saveAttachMent((Part) message[i]);
                      mail.setFilename(fileName);
                      String receivepath=mailInfo.getFilepath()+"\\"+fileName;
                      mail.setReceivepath(receivepath);
                      list.add(mail);
              }
                  return list;
          }
          }



          //接收郵件測試類

          import java.util.List;

          import org.junit.After;
          import org.junit.Before;
          import org.junit.Test;
          public class ReceiveTest{
              @Before
              public void setUp() throws Exception {
              }

              @After
              public void tearDown() throws Exception {
              }
              @Test
              public void ReceiveMailTest()throws Exception{
                  MailInfo mailInfo=new MailInfo();
                  mailInfo.setHost("pop.163.com");
                  mailInfo.setUsername("liposter");
                  mailInfo.setPassword("**********");
                  mailInfo.setFilepath("D:\\image");
                  List<MailInfo> list=new PraseMimeMessage().receive(mailInfo);
                  for(int i=0;i<list.size();i++){
                      System.out.println("Mailnumber="+list.get(i).getMailnumber());
                      System.out.println("Subject="+list.get(i).getSubject());
                      System.out.println("Content="+list.get(i).getContent());
                      System.out.println("Filename="+list.get(i).getFilename());
                      System.out.println("SentDate="+list.get(i).getSentdate());
                      System.out.println("Messageid="+list.get(i).getMessageid());
                      System.out.println("ExistsFile="+list.get(i).isExistsFile());
                      System.out.println("Read="+list.get(i).isRead());
                      System.out.println("Replysign="+list.get(i).isReplysign());
                      System.out.println("Receivepath="+list.get(i).getReceivepath());
                      System.out.println("FromAddress="+list.get(i).getFromAddress());
                      System.out.println("ToAddress="+list.get(i).getToAddress());
                  }
                  
                  
              }

          }
          posted @ 2011-10-18 00:00 abin 閱讀(3244) | 評論 (0)編輯 收藏

          郵件發送和接收已經全部實現,大家在轉發市請注明出處(我這也是參考了N多大牛的作品):

          //發送郵件類:

          import java.util.Properties;

          import javax.activation.DataHandler;
          import javax.activation.DataSource;
          import javax.activation.FileDataSource;
          import javax.mail.BodyPart;
          import javax.mail.Message;
          import javax.mail.Multipart;
          import javax.mail.Session;
          import javax.mail.Transport;
          import javax.mail.internet.InternetAddress;
          import javax.mail.internet.MimeBodyPart;
          import javax.mail.internet.MimeMessage;
          import javax.mail.internet.MimeMultipart;
          import javax.mail.internet.MimeUtility;

          public class SendMail {
              
              public boolean Send(MailInfo mailInfo)throws Exception{
                  Properties props=new Properties();
                  //設置發送郵件的郵件服務器的屬性(這里使用網易的smtp服務器)
                  props.put("mail.smtp.host", mailInfo.getHost());
                  //需要經過授權,也就是有戶名和密碼的校驗,這樣才能通過驗證(一定要有這一條)
                  props.put("mail.smtp.auth", mailInfo.getValidate());
                  Session session=Session.getDefaultInstance(props);// 用剛剛設置好的props對象構建一個session
                  session.setDebug(true);
                  MimeMessage message=new MimeMessage(session);
                  try{
                      message.setFrom(new InternetAddress(mailInfo.getFromAddress()));
                      message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailInfo.getToAddress()));
                      message.setSubject(mailInfo.getSubject());
                      message.setSentDate(mailInfo.getSentdate());
                      //向multipart對象中添加郵件的各個部分內容,包括文本內容和附件
                      Multipart multipart=new MimeMultipart();
                      BodyPart contentPart=new MimeBodyPart();
                      contentPart.setText(mailInfo.getContent());
                      multipart.addBodyPart(contentPart);
                      //添加附件
                      if(mailInfo.getFilepath()!=null){
                          BodyPart messageBodyPart=new MimeBodyPart();
                          DataSource source=new FileDataSource(mailInfo.getFilepath());
                          
                          messageBodyPart.setDataHandler(new DataHandler(source));
                          sun.misc.BASE64Encoder enc=new sun.misc.BASE64Encoder();
                          String fname=mailInfo.getFilename();
                          if(fname!=null){
                              messageBodyPart.setFileName("=?GBK?B?"+enc.encode(fname.getBytes())+"?=");
                      //        messageBodyPart.setFileName(MimeUtility.encodeText(fname));
                              multipart.addBodyPart(messageBodyPart);
                          }else{
                              String lname=mailInfo.getFilepath().substring(mailInfo.getFilepath().lastIndexOf("\\")+1, mailInfo.getFilepath().length());
                              System.out.println(lname);
                              messageBodyPart.setFileName("=?GBK?B?"+enc.encode(lname.getBytes())+"?=");
                      //        messageBodyPart.setFileName(MimeUtility.encodeText(lname));
                              multipart.addBodyPart(messageBodyPart);
                          }
                          
                      }

                      
                      message.setContent(multipart);//text/plain表示純文本內容
                      message.saveChanges();
                      Transport transport=session.getTransport("smtp");
                      transport.connect(mailInfo.getHost(),mailInfo.getUsername(),mailInfo.getPassword());
                      transport.sendMessage(message,message.getAllRecipients());
                      transport.close();
                      return true;
                  }catch(Exception e){
                      e.printStackTrace();
                  }
                  
                  return false;
              }
          }



          //測試郵件發送類
          import org.junit.After;
          import org.junit.Before;
          import org.junit.Test;

          public class SendTest {

              @Before
              public void setUp() throws Exception {
              }

              @After
              public void tearDown() throws Exception {
              }
              @Test
              public void mailTest(){
                  SendMail mail=new SendMail();
                  MailInfo mailInfo=new MailInfo();
                  mailInfo.setContent("郵件內容44444444444444444444");
                  mailInfo.setFilepath("E:\\Emotion\\Photo\\乳溝.jpg");
                  String fname=mailInfo.getFilepath().substring(mailInfo.getFilepath().lastIndexOf("."), mailInfo.getFilepath().length());
                  System.out.println(fname);
          //        mailInfo.setFilename("希望"+fname);
                  mailInfo.setFromAddress("leeposter@163.com");
                  mailInfo.setHost("smtp.163.com");
                  mailInfo.setSubject("郵件主題444444444444444444444");
                  mailInfo.setToAddress("liposter@163.com");
                  mailInfo.setUsername("leeposter");
                  mailInfo.setValidate("true");
                  mailInfo.setPassword("*********");
                  try{
                      boolean flag=mail.Send(mailInfo);
                      if(flag==true){
                          System.out.println("發送成功");
                      }else{
                          System.out.println("發送失敗");
                      }
                  }catch(Exception e){
                      e.printStackTrace();
                  }
                  
                  
              }

          }
          posted @ 2011-10-17 23:56 abin 閱讀(1862) | 評論 (0)編輯 收藏

          取出前三條記錄:
          select * from notebook fetch first 3 row only
          posted @ 2011-09-25 23:32 abin 閱讀(1881) | 評論 (2)編輯 收藏

          僅列出標題
          共50頁: First 上一頁 42 43 44 45 46 47 48 49 50 
          主站蜘蛛池模板: 如皋市| 个旧市| 东山县| 靖江市| 昌宁县| 南部县| 汕头市| 红原县| 墨竹工卡县| 湘潭市| 治多县| 出国| 离岛区| 五原县| 武邑县| 常山县| 托里县| 浪卡子县| 乌恰县| 武功县| 开封市| 明水县| 女性| 天门市| 建平县| 淳化县| 偏关县| 丁青县| 东丰县| 金川县| 肇源县| 陆丰市| 西盟| 桑植县| 互助| 定州市| 安徽省| 福泉市| 兴义市| 双江| 腾冲县|