天天看點

javamail接收郵件(較全代碼)

java 代碼

import java.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) {

    /**  

     * 獲得發件人的位址和姓名  

     */  

    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 = "";   

                        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) {

        } 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;

        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 = iscontainattach((part) part.getcontent());   

        return attachflag;   

     * 【儲存附件】   

    public void saveattachment(part part) throws exception {

        string filename = "";   

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

                    if ((filename != null)

                            && (filename.tolowercase().indexof("gb2312") != -1)) {

                        savefile(filename, mpart.getinputstream());   

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

    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 + " 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]);   

}